Getting started with PyQt5
1. Use Qt designer
View pyQt5 + pycharm configuration installation
PyQt5
,PyQt5-tools
useQt designer
to generate ui files andPyUic
convert them intopy
files using tools
1.1 Configure Qt designer external tools: two ways
pyqt5-tools.exe
:pyqt5-tools.exe designer
2. designer.exe
1.2 Configure PyUIC external tools
1.3 Add entry main running result
import sys
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
2. Simple window
QtWidgets.QApplication(sys.argv) provides the underlying management functions of the entire graphical interface program, such as:
initialization, processing of program entry parameters, distribution of user events (click, input, drag on the interface) to each corresponding control, etc. wait…
- Every PyQt5 application must create an application object. sys.argv is a list of command line arguments. Python can be run in the shell, and this parameter provides the function of script control.
app.exec_()
Entering the main loop of the application, the event handler starts working at this time. The main loop receives events from the window and dispatches the events to the application controls. The main loop ends when the exit() method is called or the main control is destroyed directly.sys.exit()
This method ensures that the main loop exits safely. The external environment receives information about how the main control ended up.
The main window of the QtWidgets.QMainWindow()
QMainWindow(QWidget)
interface, inherited ,MainWindow.show()
allows the control to be displayed on the desktop;QtWidgets.QWidget(MainWindow)
the QWidge control is a basic control of the user interface, which provides a basic application constructor. By default, a constructor has no parent, and a constructor without a parent is called a window.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'app.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
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, 22))
self.menubar.setObjectName("menubar")
self.menu = QtWidgets.QMenu(self.menubar)
self.menu.setObjectName("menu")
self.menu_2 = QtWidgets.QMenu(self.menubar)
self.menu_2.setObjectName("menu_2")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.menubar.addAction(self.menu.menuAction())
self.menubar.addAction(self.menu_2.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.menu_2.setTitle(_translate("MainWindow", "新建"))
2.1 With window icon
The window icon is usually displayed in the upper left corner of the window and at the far left of the title bar. Prepare the picture
icon.ico
, create a QIcon object, set the upper left corner iconMainWindow.setWindowIcon()
, andsetWindowTitle
set the upper left corner title; the above two methods are inherited from the QWidget class
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
# ... ...
MainWindow.setWindowTitle("XhNote")
icon = QIcon("icons/icon.ico")
MainWindow.setWindowIcon(icon)
# ... ...
2.2 Prompt box
QToolTip.setFont(QFont('SansSerif', 10))
This static method sets the font of the prompt box. We use the 10px SansSerif font.
mainQwidget.setToolTip('This is a <b>QWidget</b> widget')
Central widget mouseover prompt
btn.setToolTip('This is a <b>QPushButton</b> widget')
Button mouseover prompt
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import QPushButton, QToolTip
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
# ... ...
mainQwidget = QtWidgets.QWidget(MainWindow)
QToolTip.setFont(QFont('SansSerif', 10))
mainQwidget.setToolTip('This is a <b>QWidget</b> widget')
btn = QPushButton('Button', mainQwidget)
btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.resize(btn.sizeHint())
btn.move(50, 50)
mainQwidget.setWindowTitle('Tooltips')
#
self.centralwidget = mainQwidget
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
# ... ...
2.3 Close the window
qbtn.clicked.connect(QCoreApplication.instance().quit)
The event delivery system is built into PyQt5single和slot机制
. When the button is clicked, the signal is captured and a given response is given.QCoreApplication
Contains the main event loop, which adds and removes all events andinstance()
creates an instance of it.QCoreApplication
wasQApplication
created in. The click event is bound to the quit function that terminates the process and exits the application. Communication is established between the sender and the receiver. The sender is the button and the receiver is the application object.
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QPushButton
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
# ... ...
mainQwidget = QtWidgets.QWidget(MainWindow)
qbtn = QPushButton('退出', mainQwidget)
qbtn.clicked.connect(QCoreApplication.instance().quit)
#
self.centralwidget = mainQwidget
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
# ... ...
2.4 Message box
By default, when we click the × button in the title bar, the QWidget will close. But sometimes, we modify the default behavior. For example, if we open a text editor and make some changes, we will want to ask the user to further confirm the operation when closing the button.
If it is closedQWidget
, one will be generatedQCloseEvent
and passed intocloseEvent
the event parameter of the function. To change the default behavior of a control is to replace the default event handling.
We created a message boxQMessageBox.question()
with two buttons: Yes and No. The first string is displayed in the title bar of the message box, the second string is displayed in the dialog box, and the third parameter is the two buttons of the message box. The last parameter is the default button, which is selected by default. The return value is in the variable reply.
import sys
from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication, QDesktopWidget
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Message box')
self.center()
self.show()
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def closeEvent(self, event):
reply = QMessageBox.question(self, 'Message',
"Are you sure to quit?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
2.5 Window centering
QtGui.QDesktopWidget
Provides the user's desktop information, including screen size.qr = self.frameGeometry()
Get the frame where the main window is located.cp = QDesktopWidget().availableGeometry().center()
Get the resolution of the monitor and then get the position of the middle point of the screen.qr.moveCenter(cp)
Then place the center point of the main window frame to the center of the screen.self.move(qr.topLeft())
Then use the move function to move the upper left corner of the main window to the upper left corner of its frame, thus centering the window.
(qr.moveCenter(cp)
After commenting, the window will be displayed in the upper left corner of the screen)
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QPushButton, QDesktopWidget
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
# ... ...
self.center(MainWindow)
def center(self, MainWindow):
qr = MainWindow.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
MainWindow.move(qr.topLeft())