Table of contents
1. Write in front
~~~~~~~~~ Recently, I plan to start systematically sorting out the basic knowledge and skills of python for QT development. On the one hand, I will help teachers sort out relevant knowledge and example demos. On the other hand, I will also improve my own knowledge of QT development, as a supplement and expansion of the previous QT tree components. For the basic content of QT tree components, you can refer to my previous blog post: https://blog.csdn.net/DALEONE/article/details/123676385?spm=1001.2014.3001.5501
2. Basic components of QT for Python
2.1 QPushButton component
-
Component Introduction:
~~~~~~~~~ The QPushButton component, as its name implies, is the class that defines the buttons in the QT interface. The QT official website defines it as Perhaps the most commonly used widget in user's interface, which shows its importance in the development and design of the QT interface, but from the perspective of application development, It is relatively simple.
-
Interface display:
-
Components use:
-
The instantiation and basic use of QPushButton:
button1 = QPushButton("OK", self) ## QPushButton实例化 button1.clicked.connect(lambda: self.onClicked(button1)) def onClicked(self, button): print("Button {0} is clicked.".format(button.text()))
Small Tips:
- In the constructor of QPushButton, str is passed in as the label of the Button, which is displayed on the successfully created button
- The text method of Button is used to get the name of Button (the label passed in when instantiated above)
The connect function here emphasizes:
~~~~~~~~ In the QT development process, each component cannot exist alone, and must be associated with a certain effect (not just put an icon on it, otherwise the graphical interface will be meaningless).
That is
Button.clicked.connect()
to explain the associated function behind the Button button:print("Button {0} is clicked.".format(button.text()))
output the name of the pressed button.remind:
Here the onClicked function needs to pass in parameters, so the function is passed in with the help of lambda expressions, and there will be other ways to pass in other components later
Regarding lambda expressions, you can also refer to my blog post: (2 messages) Detailed explanation of the basic usage of lambda expressions, list generation, and map() functions in python_Neighbor Li Xuechang's blog-CSDN blog_lambda list
-
Other uses of QPushButton:
-
The setText() function modifies the label information of the Button:
There are two ways to set the button Button:
- Directly passed in when the constructor method is instantiated
- The button is modified by means of the setText method
-
QPushButton shortcut key settings:
~~~~~~~~ The QPushButton official website provides a shortcut key setting method. Add "&" before the Button label. Note that the shortcut key at this time is determined by the Alt key and the first letter after &.
button1.setText("&help")
- According to the above explanation, the shortcut key of Button1 at this time is Alt+h
- As a reminder, use && for real &
-
Default button setting setAutoDefault
~~~~~~~~ The description given on the official website about the default key setting is
A default btton is a push button that is activated when the user presses the Enter or Return key in the dialog
, simply put: set the existing button as the default, and it will be activated by default when the user presses Enter or Returnbutton1.setAutoDefault(True)
-
OK, all the above content about QPushButton has been explained, the complete code:
import sys from PyQt5.QtWidgets import QApplication, QPushButton, QWidget class MainWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) button1 = QPushButton("OK", self) ## 创建名为ok的Button ## label的内容可以在构造函数创建,也可借助于setText函数实现后期修改 button1.setText("help") ## 设置默认按键驱动Button(Enter or Return key in the dialog) button1.setAutoDefault(False) ## 快捷键设置(简单的快捷键的设置方法:字母前加&,快捷键即为alt+字母) # button1.setText("&help") button1.clicked.connect(lambda: self.onClicked(button1)) def onClicked(self, button): print("Button {0} is clicked.".format(button.text())) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWidget() window.resize(400, 200) window.show() sys.exit(app.exec_())
-
2.2 QMessageBox component
-
Component Introduction:
~~~~~~~~
QMessageBox
It is mainly used to pop up a dialog box to display information prompts and guide users. The definition given by the official document isThe QMessageBox class provides a modal dialog for informing the user or for asking the user a question and receiving an answer
that it simply translates to give user information, ask user questions, and receive user input. -
Interface display:
-
Component application:
~~~~~~~~
QMessageBox
QT
It is also very common in creation, and it is widely used in warning boxes, confirmation boxes, etc. The following twoQMessageBox
construction methods are mainly introduced:-
With the help of static functions information, critical, question, warning
ret = QMessageBox.question(self, "question Message", "The document has been modified.\n Do you want to save your changes?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, QMessageBox.Save)
The above code shows how to realize the creation of the query dialog box with the help of static functions
Small
Tips:
- A few notes about
question
functions:
Regarding
question
the function, the official website gives two construction methods, a brief summary:question(parent,title,text,button1,button2)
, the return value isint
question(parent,title,text,buttons,defaultButton)
, the return value isStandardButton
In this example, the overloaded
question
method is used, whichQMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel
means thatButtons
QMessageBox.Save
defaultButton
This point can be explained in the code
print('type(ret)')
, and the output value is found<class 'PyQt5.QtWidgets.QMessageBox.StandardButton'>
(although the code is directly output as a number here)buttons
Notes on neutralization of overloaded functionsdefaultButton
:
buttons
Use|
connections to indicate buttons that will be displayed directly in the dialog, anddefaultButton
to indicate the button case by defaultquestion,warning,critical,information
The button creation and usage methods are similar, the only difference is that the graphic display on the left side of the dialog box is different. For details, please refer to the official document
- A few notes about
-
Create it yourself with the help of the function definition method:
~~~~~~~~ Similar to QFileDialog, the creation of methods defined by functions is more free and less restrictive than static methods, but the difficulty and complexity of creation is higher than that of static methods.
msgBox = QMessageBox() # QMessageBox class 实例化 msgBox.setText("The document has been modified.") msgBox.setInformativeText("Do you want to save your changes?") msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Save) msgBox.setDetailedText("这是一个测试用例\n用于测试setDetailedText的具体用法") ret = msgBox.exec() print(ret == QMessageBox.Save)
Small
Tips:
setText
andsetInformativeText
can be used to set the information displayed in the dialog box,str
just pass in the type string internallysetStandardButtons
and aresetDefaultButton
used to set the standard button and the default button respectively, the same as when the static method was createdsetDetailedText
It is used to add detailed information. After calling the function,show Details
a button will be automatically added to the dialog box. After clicking, the detailed information will be displayed, andstr
a string can be passed in internally.ret = msgBox.exec()
Used to call the dialog box, this function must be called, otherwise the dialog box will not be displayed and no effect will be seenret
Used to receive the return value of the function (the button clicked by the user), therefore, assuming the user clicks at this timesave
,print
the output value istrue
~~~~~~~~ OK, all the above content about the QMessageBox component has been introduced, and the complete code is provided for your reference:
import sys from PyQt5.QtWidgets import QApplication, QMessageBox, QWidget, QPushButton class MainWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) button = QPushButton("OK", self) ## 界面中设置一个Button self.resize(800, 600) button.clicked.connect(self.onOKClicked) def onOKClicked(self): msgBox = QMessageBox() ## 显示信息 msgBox.setText("The document has been modified.") msgBox.setInformativeText("Do you want to save your changes?") ## 小界面中设置Button msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Save) # 设置详细信息的显示,会自动添加Button按钮 msgBox.setDetailedText("这是一个测试用例\n用于测试setDetailedText的具体用法") ## ret本质上会返回用户选择的按钮 ret = msgBox.exec() print(ret == QMessageBox.Save) '''借助于静态函数进行实例化''' # ## warning的弹出框 # ret = QMessageBox.warning(self, "Warning Message", # "The document has been modified.\n Do you want to save your changes?", # QMessageBox.Save | QMessageBox.Discard # | QMessageBox.Cancel, # QMessageBox.Save) # ## information的弹出框 # ret = QMessageBox.information(self, "Information Message", # "The document has been modified.\n Do you want to save your changes?", # QMessageBox.Save | QMessageBox.Discard # | QMessageBox.Cancel, # QMessageBox.Save) # # ## question的弹出框 # ret = QMessageBox.question(self, "Question Message", # "The document has been modified.\n Do you want to save your changes?", # QMessageBox.Save | QMessageBox.Discard # | QMessageBox.Cancel, # QMessageBox.Save) # ## critical的弹出框 # ret = QMessageBox.critical(self, "critical Message", # "The document has been modified.\n Do you want to save your changes?", # QMessageBox.Save | QMessageBox.Discard # | QMessageBox.Cancel, # QMessageBox.Save) # print(type(ret)) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWidget() window.resize(400, 200) window.show() sys.exit(app.exec_())
-
2.3 QInputDialog component
-
Component Introduction:
~~~~~~~~
QInputDialog
The component is a dialog box that can receive user input. The explanation given by the official website is:The QInputDialog class provides a simple convenience dialog to get a single value from the user
, translated to provide a convenient dialog box for receiving user input. -
Interface display:
-
Component application:
~~~~~~~~
QInputDialog
Same as the above components, it also provides static functions to conveniently create dialog instances. The provided static functions mainly includegetDouble() , getInt() , getItem() , getText() , getMultiLineText()
the following. We mainly introduce two of them to illustrate the usage of this static function:-
getInt() static function:
num, ok = QInputDialog.getInt(self, "Input an int number", "num:") if ok: print("input num: ", num)
getMultiLineText() static function:
text, ok = QInputDialog.getMultiLineText(self, "Input MultiLineText", "Text:") if ok: print("input text: ", text)
A little about the above functions
Tips:
- You will find that
getInt(),getMultiLineText()
the calling methods are basically the same. In fact, the calling methods of other static functions are similar (the parameters passed in by the functions mentioned below aregetItem()
somewhat different from others) - The input parameters of the static function mainly include two:
Input an int number
the title of the pop-up window,num:
and the specific content displayed in the dialog box - There are two return values of the static function:
value
andok标签
,value
indicating the content entered by the user (can be a number, a string, etc.),ok
and the returnbool
value, indicating whether the user makes a selection - The above shows are the basic usage. For more detailed usage and functions, please refer to the official document. The reference link: https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QInputDialog.html
- You will find that
-
getItem() static function:
items = ["C++", "Python", "Java", "Go"] item, ok = QInputDialog.getItem(self, "Select an Item", "Programing Language", items, 0, False) if ok and item: print("selected item: ", item)
Small
Tips:
getItem()
The function is the same as other static functions, and it also provides a dialog box for the user to choose, but the difference is thatgetItem
the user is given a range to choose from, rather than the user inputting at will- getItem() accepts more input parameters. The first two
text
are the same, indicating the title and specific content of the dialog box respectively. Next, three parameters need to be received. Theitems---list,current---int,editable---bool
three parameters respectively represent the list to be selected for the user to choose. The list displays the note by default. index, whether it can be edited - The return value
getInt()
is the same as above, for more details, refer to the official documentation
The introduction of the above-mentioned QInputDialog has been completed, and the complete code is convenient for everyone to refer to:
import sys from PyQt5.QtWidgets import QApplication, QInputDialog, QWidget, QPushButton class MainWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) button = QPushButton("OK", self) self.resize(800, 600) button.clicked.connect(self.onOKClicked) def onOKClicked(self): # QInputDialog提供多个用户选择getItem,getText,getInt,getDouble items = ["C++", "Python", "Java", "Go"] item, ok = QInputDialog.getItem(self, "Select an Item", "Programing Language", items, 1, True) if ok and item: print("selected item: ", item) text, ok = QInputDialog.getText(self, "Input an text", "text:") if ok: print("input text: ", text) num, ok = QInputDialog.getInt(self, "Input an int number", "num:") if ok: print("input num: ", num) text, ok = QInputDialog.getMultiLineText(self, "Input MultiLineText", "Text:") if ok: print("input text: ", text) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWidget() window.resize(400, 200) window.show() sys.exit(app.exec_())
-
2.4 QFileDialog component
-
Component Introduction:
~~~~~~~~ In my impression, this component should be
树形组件博文
briefly introduced in , and the official website defines it asThe QFileDialog class provides a dialog that allows users to select files or directories
, in translation, it provides a dialog box for users to select files or directories. -
Interface display:
-
Component application:
~~~~~~~~ On the official website, QFileDialog provides two construction methods: 1. With the help of static functions -
static function
2. Create by yourself-
With the help of static functions
getOpenFileName
fname, _ = QFileDialog.getOpenFileName(self, "Open file", 'C:/Users\腻味\Desktop\ClashForWindows', "Images(*.jpg *.gif);;Text files (*.txt)") # 选择文件并将选择的文件路径进行返回 print(fname)
Small
Tips:
- Several commonly used parameters:
caption:{str}
Corresponds to"open file"
the name used to define the open windowdir:{str}
Used to define the default file path for opening windowsselectedFilter:{str}
An optional type used to define the file to operate on- Function return value:
fileName,selectedFilter
The _ in the original code stands for selectedFilter, and the underscore means we don’t care, but the original function does return, so it occupies a place- other:
The official document is always the best reference document, see the official document for more optional parameters of getOpenFileName, Portal: QFileDialog — Qt for Python
-
Create your own with the help of functions
~~~~~~~~ Compared with using the official static functions, the method of self-creation with the help of functions is obviously more complicated, but the advantage of using this method is that it has small restrictions and great operability
fileNames = [] dialog = QFileDialog(self) # QFileDialog类实例化 dialog.setFileMode(QFileDialog.AnyFile) ## 指定打开的文件类型:源代码中添加tr,但查阅相关资料后发现tr可以不适用,且一般情况下不推荐使用 # 参考文献:https://blog.csdn.net/weixin_41567783/article/details/118416484 dialog.setNameFilter("Images (*.png *.xpm *.jpg)") ## 理论上,list仅显示文件名和文件夹列表,而Details同时显示详细信息(文件大小,修改时间等) # dialog.setViewMode(QFileDialog.Detail) # dialog.setViewMode(QFileDialog.List) dialog.setDirectory('C:/Users\腻味\Pictures\Saved Pictures') ## 此函数可以设计打开时的文件夹
Small
Tips:
setFileMode
Functions are used for settingFileMode
, there are three modes to choose from here:AnyFile,ExistingFile,Directory
AnyFile
Any type can be selected, even non-existing files, so it is often used insave as
class dialogsExistingFile
Optional files that do existDirectory
Optional directory, not optional specific file
setNameFilter
It is used to specify the optional format of the file. If you read the source code, you will find that the string in the source code is prependedtr
, but you can’t findtr
the relevant definition after consulting the data. Finally, it is mentioned in a blog post:tr
it seems to be a module designed to facilitate language switching. Here can not be used everywhere
Reference:
https://blog.csdn.net/weixin_41567783/article/details/118416484setViewMode
Set the display information of the file. According to the official document, it contains two modesQFileDialog.Detail和QFileDialog.List
, one only displays the file list, and the other can display the detailed information of the file (such as file size, modification time, etc.), but from the actual running effect of the code Observation, did not play a role, no matter what is setMode
, the final display is detailed informationSetDirectory
It is used to set the default file path to open the dialog box, and the internal parametersDirPath
can be passed in- For more information, refer to the official documentation
The above-mentioned introduction about QFileDialog is fully completed, and the complete code is attached for your reference:
## QFileDialog模块学习 import sys from PyQt5.QtWidgets import QApplication, QFileDialog, QWidget, QPushButton class MainWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) button = QPushButton("选择文件", self) self.resize(800,600) button.clicked.connect(self.onOKClicked) def onOKClicked(self): '''1. Using a static function-getOpenFileName''' # fname, _ = QFileDialog.getOpenFileName(self, "Open file", 'C:/Users\腻味\Desktop\ClashForWindows', "Images(*.jpg *.gif);;Text files (*.txt)") # 选择文件并将选择的文件路径进行返回 # print(fname) '''2. creat our own QFileDialog''' fileNames = [] # 首先赋值为empty directory dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("Images (*.png *.xpm *.jpg)") # # dialog.setViewMode(QFileDialog.Detail) # # dialog.setViewMode(QFileDialog.List) dialog.setDirectory('C:/Users\腻味\Pictures\Saved Pictures') if dialog.exec_(): fileNames = dialog.selectedFiles() print(fileNames) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWidget() window.resize(400, 200) window.show() sys.exit(app.exec_())
-
~~~~~~~~ Here as a dividing line, the above mainly introduces the core modules in QT development, and the following introduces some small components:
2.5 QtextEdit component
-
Component Introduction:
~~~~~~~~ The QtextEdit component is also an important and commonly used component in QT development, as defined in the official documentation
QtextEdit class provides a widget which is used to edit and display plain and rich text
. The translated QtextEdit component provides a component for displaying or editing plain text and rich text. -
Interface display:
-
Component application:
import sys from PyQt5.QtWidgets import QApplication, QTextEdit, QWidget, QLabel from PyQt5.QtCore import Qt from PyQt5.QtGui import QIntValidator class MainWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) label = QLabel("input: ", self) label.move(0, 0) self.textEdit = QTextEdit(self) self.textEdit.move(100, 0) self.textEdit.setPlainText("Hello, PyQt5") self.textEdit.textChanged.connect(self.displayText) def displayText(self): print(self.textEdit.toPlainText()) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWidget() window.resize(400, 200) window.show()
Small Tips:
The above code shows the basic usage of QtextEdit, mainly involving two functions:
- setPlainText() is used to display plain text content "hello PyQt5" in the component
- The textChanged.connect() function is used to print the text content of the component when the content of the component changes. The form and function of the call are similar to the QPushButton component
2.6 QSlider component
-
Component Introduction:
~~~~~~~~ The QSlider component provides interactive selection of data by sliding up, down or left and right. It is widely used in some specific scenarios in QT development.
-
Interface display:
-
Component application:
import sys from PyQt5.QtWidgets import QApplication, QSlider, QWidget from PyQt5.QtCore import Qt class MainWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) ## 水平滑栏 # slider = QSlider(Qt.Horizontal, self) ## 竖直滑栏 slider = QSlider(Qt.Vertical, self) ## 设置Slider的上下限 slider.setMaximum(20) slider.setMinimum(10) slider.valueChanged.connect(self.onValueChanged) def onValueChanged(self, value): print("current value is {0}".format(value)) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWidget() window.resize(400, 200) window.show() sys.exit(app.exec_())
Small Tips:
-
The QSlider component is mainly divided into two ways: horizontal and vertical. When the constructor is constructed, different parameters are passed in to create a horizontal or vertical Slider.
Qt.Horizontal represents horizontal, Qt.Vertical represents vertical
-
The setMaximum and setMinimum functions are used to set the maximum and minimum values during the sliding process of the slider respectively
-
valueChanged.connect() is used to output the corresponding selected value when the selected value of the slider changes
-
2.7 QSpinBox component
-
Component Introduction:
~~~~~~~~ The QSpinBox component provides a set of discrete value sets for users to choose,
handle integers or discrete sets of values
and the personal understanding function is not much different from the above QSlider, with different effects. -
Interface display:
-
Component application:
import sys from PyQt5.QtWidgets import QApplication, QSpinBox, QWidget class MainWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) spinBox = QSpinBox(self) ## SpinBox各种方法测试 spinBox.setMinimum(10) spinBox.setMaximum(20) ## 设置调整的步长 spinBox.setSingleStep(2) ## 循环操作 spinBox.setWrapping(True) ## valueChanged信号函数 spinBox.valueChanged.connect(self.onValueChanged) ## 将选择的数据进行返回 def onValueChanged(self, value): print("current value is {0}".format(value)) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWidget() window.resize(400, 200) window.show() sys.exit(app.exec_())
Small Tips:
- spinBox also has setMinimum() and setMaximum() functions for setting the upper and lower limits of value selection
- The setSingleStep() function internally passes in a value, which is used to set the step size of one adjustment (click once, how much the value changes)
- The setWrapping() function is used to set whether there will be a loop in the process of numerical transformation (that is, whether to click after reaching the maximum value will return to the minimum value)
- The valueChanged.connect() function is consistent with the calling method and function of the original QPushButton
2.8 QComboBox component
-
Component Introduction:
~~~~~~~~ The QComboBox component is used to construct a drop-down box in the development of a graphical interface, so that users can choose from several items set in advance by the developer.
-
Interface display:
-
Component application:
import sys from PyQt5.QtWidgets import QApplication, QComboBox, QWidget class MainWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) self.combo = QComboBox(self) ## 添加元素addItem self.combo.addItem("Apple") self.combo.addItem("HuaWei") self.combo.addItem("XiaoMi") self.combo.addItem("Oppo") ## 添加元素insertItem(index,str) self.combo.insertItem(1,"Meizu") ## 修改元素setItemText(index,str) self.combo.setItemText(1,"Chuizi") ## 删除元素removeItem(index) # self.combo.removeItem(1) ## 清除所有元素clear(all items can be removed) ## 获取指定index处的标签itemText(idnex) # string = self.combo.itemText(1) # print(string) ## comboBox每个词条内容可编辑 # self.combo.setEditable(True) ## 设置内容是否可以重复 # self.combo.setDuplicatesEnabled(True) self.combo.currentIndexChanged.connect(self.onCurrentIndex) def onCurrentIndex(self, index): ## 获取当前词条的标签内容 print("current item is {0}".format(self.combo.currentText())) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWidget() window.resize(400, 200) window.show() sys.exit(app.exec_())
Small Tips:
-
Two functions for adding entries to QComboBox : addItem and insertItem
addItem(item) adds entries in order from top to bottom
insertItem(index,item) can insert the entry at the specified index position
-
QComboBox modify entry: setItemText(index,item)
-
QComboBox delete and clear function: remove(index), clear()
-
itemText(index) is used to get the label label of the element at the specified entry
-
setEditable() and setDuplicatesEnabled() are used to set whether the item entry in QComboBox() is editable and repeatable
-
currentText() combines currentIndexChanged to print the entry content selected by the user on the screen
-
3. Summary
~~~~~~~~ The above briefly introduces and summarizes the basic usage of commonly used components when using Python for QT development, but they are only superficial and far from reaching the level of development. The author is trying to use the above components to develop an overall interface recently. Readers are also recommended to try it by themselves. Only after developing a small system can they really master this technology. Let's work hard together.
~~~~~~~~ The author is learning for the first time, if there are fallacies, criticize and correct! ! ! !
~~~~~~~~ All codes have been uploaded to github
: QT component code-github