Skip to content

[PyQt5] Tutorial(4) Menu, Toolbar

Last Updated on 2021-04-12 by Clay

A good interface usually has a menu, so that we can use various functions for our program. Although the smaller interface doesn't need this function, I have been researching my notation program recently, so also studied the use of "menu", "toolbar" and so on.

I want to wait until the day when my go board application is completed, and I will record it as a note in form of "combat sharing".

So, here are my notes today: how to use menus, toolbars, etc.


Menu

Before we get started, let me explain one thing: I usually do the interface and separate programs, so if you want to test my program, just take the python file. Test it, you don't have to use Qt Designer. (Of course the PyQt5 package is definitely there.)

First, I test Qt Designer to create a interface.

You can notice that I added a "File" menu in Type Here in the upper right corner.

This is the "menu" we are going to talk about.

I also created the options in the menu:

After saving and converting, we will get a file like this:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Menu.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25))
        self.menubar.setObjectName("menubar")
        self.menu = QtWidgets.QMenu(self.menubar)
        self.menu.setObjectName("menu")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionNew_File = QtWidgets.QAction(MainWindow)
        self.actionNew_File.setObjectName("actionNew_File")
        self.actionOpen_File = QtWidgets.QAction(MainWindow)
        self.actionOpen_File.setObjectName("actionOpen_File")
        self.actionClose = QtWidgets.QAction(MainWindow)
        self.actionClose.setObjectName("actionClose")
        self.menu.addAction(self.actionNew_File)
        self.menu.addAction(self.actionOpen_File)
        self.menu.addAction(self.actionClose)
        self.menubar.addAction(self.menu.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.menu.setTitle(_translate("MainWindow", "文件"))
        self.actionNew_File.setText(_translate("MainWindow", "New File"))
        self.actionOpen_File.setText(_translate("MainWindow", "Open File"))
        self.actionClose.setText(_translate("MainWindow", "Close"))


Unlike the previous file, this time we set the Menu not under setupUi(), but below the retranslateUi() we have been ignoring. However, of course, the method of use is not much different from the previously defined components.

We write this code in our own script:

# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui, QtCore
from Menu import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Menu
        self.ui.retranslateUi(self)
        self.ui.actionClose.setShortcut('Ctrl+Q')
        self.ui.actionClose.triggered.connect(app.exit)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


Output:

We can see nothing!
pressed the "file" button and we will see like this.

We are currently in the front of our own scripts. New File, Open File has not done any functions yet. The only thing that is done is Close, because it is more convenient to demonstrate. Hahahaha. Write the code like this:

In our program, first, we can use setShortcut() to make simple shortcuts.
The following line:
self.ui.actionClose.triggered.connect(app.exit)
The application ends when it is triggered.

Of course, if you want to have other features, and so on, use triggered.connect() to trigger pre-written functions.

Our simple menu button is complete.

If you want to add a graphic to the interface, you can use QIcon that we have taught before.

Add a line to the code:

self.ui.actionClose.setIcon(QtGui.QIcon('pic/Cancel.png'))


Pic is the name of the folder where I put the picture, and Cancel.png is the picture I want to put.

Output:

We can see that the menu is preceded by an X icon!


Toolbar

After finishing the Menu, the field of the "Toolbar" is almost the same; usually the toolbar is just set to the icon button of the Menu, and clicking will produce similar functions.

First, I used the ToolBar component. The ToolBar is a great way to put components together, and even add new pages to switch between different tool fields.

As you can see here, I put two ToolButtons into this ToolBar. Then we archive.

After converting to a Python file, it looks like this:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Menu.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.toolBox = QtWidgets.QToolBox(self.centralwidget)
        self.toolBox.setGeometry(QtCore.QRect(0, 0, 91, 551))
        self.toolBox.setObjectName("toolBox")
        self.page = QtWidgets.QWidget()
        self.page.setGeometry(QtCore.QRect(0, 0, 91, 491))
        self.page.setObjectName("page")
        self.toolButton = QtWidgets.QToolButton(self.page)
        self.toolButton.setGeometry(QtCore.QRect(0, -10, 91, 81))
        self.toolButton.setText("")
        self.toolButton.setObjectName("toolButton")
        self.toolButton_2 = QtWidgets.QToolButton(self.page)
        self.toolButton_2.setGeometry(QtCore.QRect(0, 70, 91, 81))
        self.toolButton_2.setObjectName("toolButton_2")
        self.toolBox.addItem(self.page, "")
        self.page_2 = QtWidgets.QWidget()
        self.page_2.setGeometry(QtCore.QRect(0, 0, 91, 221))
        self.page_2.setObjectName("page_2")
        self.toolBox.addItem(self.page_2, "")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25))
        self.menubar.setObjectName("menubar")
        self.menu = QtWidgets.QMenu(self.menubar)
        self.menu.setObjectName("menu")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionNew_File = QtWidgets.QAction(MainWindow)
        self.actionNew_File.setObjectName("actionNew_File")
        self.actionOpen_File = QtWidgets.QAction(MainWindow)
        self.actionOpen_File.setObjectName("actionOpen_File")
        self.actionClose = QtWidgets.QAction(MainWindow)
        self.actionClose.setObjectName("actionClose")
        self.menu.addAction(self.actionNew_File)
        self.menu.addAction(self.actionOpen_File)
        self.menu.addAction(self.actionClose)
        self.menubar.addAction(self.menu.menuAction())

        self.retranslateUi(MainWindow)
        self.toolBox.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.toolButton_2.setText(_translate("MainWindow", "Hello World"))
        self.toolBox.setItemText(self.toolBox.indexOf(self.page), _translate("MainWindow", "Page 1"))
        self.toolBox.setItemText(self.toolBox.indexOf(self.page_2), _translate("MainWindow", "Page 2"))
        self.menu.setTitle(_translate("MainWindow", "文件"))
        self.actionNew_File.setText(_translate("MainWindow", "New File"))
        self.actionOpen_File.setText(_translate("MainWindow", "Open File"))
        self.actionClose.setText(_translate("MainWindow", "Close"))


Then we write the code again.

# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui, QtCore
from Menu import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)


        # Menu
        self.ui.retranslateUi(self)
        self.ui.actionClose.setShortcut('Ctrl+Q')
        self.ui.actionClose.setIcon(QtGui.QIcon('pic/Cancel.png'))
        self.ui.actionClose.triggered.connect(self.exit)

        # ToolBar
        self.ui.toolButton.setShortcut('Ctrl+E')
        self.ui.toolButton.setIcon(QtGui.QIcon('pic/Cancel.png'))
        self.ui.toolButton.clicked.connect(self.exit)

    def exit(self):
        app.exit()


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


Output:

As you can see, I added two new buttons. One of them I still set to use the same image.

We pressed this image and then we should be exit this program.

By the way, I can see that I have set two different shortcut keys. This is because the Exit button of my menu has already set a fairly shortcut key. The two shortcuts for setting the same component will give an error!

Then, Because it's a Button this time, we use clicked.connect() to bind the triggered event.

The above is the teaching of today, thank you for your attention.


I spent the night before and chatting with my friends all night, and then the whole person was very sleepy. Am I really old? I wrote a Go game yesterday morning and decided that I couldn’t write it for a long time. It’s the program I wrote a few years ago in college!

Then I went home from the lab at 8 o'clock in the evening and immediately slept. I slept until 5 o'clock in the morning and woke up. Even the article was forgotten.

Then I spurred the book (?), and deleted the judgment of the ate eating written yesterday, rewriting.

I finished the less than an hour this time, testing the graphical interface, um, OK! It looks like there are no bugs.

Very strangely, I think I am writing the same program and running!

Sure enough, I shouldn’t stay up all night to write a program. XDDDD


References


Read More

Leave a Reply