PyQt5从入门到实践——Chapter5 PyQt5常用控件

发布时间:2024年01月07日

目录

概述

1. 控件概述

2. 文本类控件

2.1 Label:标签控件

(1)设置标签文本

(2)设置标签文本的对齐方式

(3)设置文本换行显示

(4)为标签设置超链接

(4)为标签设置图片

2.2 LineEdit:单行文本框

(1)设置密码登录格式

2.3 TextEdit:多行文本框

2.4 SpinBox:整数数字选择控件

2.5 DoubleSpinaBox:小数数字选择控件

2.6 LCDNumber:液晶数字显示控件

3. 按钮类控件

3.1 PushButton:按钮

3.2 ToolButton:工具按钮

3.3 CommandLinkButton:命令链接按钮

3.4 RadioButton:单选按钮

3.5 CheckBox:复选框

4. 选择列表类控件

4.1 ComboBox:下拉组合框

4.2 FontComboBox:字体组合框

4.3 ListWidget:列表

5. 容器控件

5.1 GroupBox:分组框

5.2 TabWidget:选项卡

5.3 ToolBox:工具盒

6. 时间和日期类控件


概述

控件是窗口程序的基本组成单位,本章将对开发PyQt5窗口应用程序中经常用到的控件进行记录。

1. 控件概述

控件是用户可以用来输入或操作的对象。在PyQt5中,控件的基类是QFrame类,而QFrame类继承自QWidget类,QWidget类是所有用户界面对象的基类。

Qt Designer设计器中对控件进行了分组,下表是对各分组和控件的说明:

2. 文本类控件

2.1 Label:标签控件

(1)设置标签文本

(a)直接双击添加的Label控件直接修改(方便),或者修改text属性值

(b)代码实现方式:

self.label.setText("用户名:")

(2)设置标签文本的对齐方式

(a)属性编辑器——alignment属性,分为Horizontal(水平)和Vertical(垂直)对齐方式

(b)代码实现方式:使用QLabel类的setAlignment,麻烦,懒得写了

(3)设置文本换行显示

(a)属性编辑器——wordWrap √

(b)代码实现方式:

self.label.setWordWrap(True)

(4)为标签设置超链接

在QLabel类的setText()方法中使用HTML中的<a>标签设置超链接文本,并把Label标签的setOpenExternalLinks()方法设置为True

self.label.setText('<a href="https://www.csdn.net/">CSDN官网</a>') #CSDN官网为文本内容
self.label.setOpenExternalLinks(True)

#自定义链接样式使用style
#self.label.setText('<a style="text-decoration: none; color: black;" href="https://www.csdn.net/">CSDN官网</a>') 

(4)为标签设置图片

使用QLabel类的setPixmap()方法

from PyQt5.QtGui import QPixmap
self.label.setPixmap(QPixmap("Chapter5/back.jpg"))

2.2 LineEdit:单行文本框

(1)设置密码登录格式

实例:使用LineEdit+Label控件制作一个简单的登录窗口,其中限制密码为8位,并且以掩码形式显示。

步骤:

(a)Qt Designer设计窗口界面

(b)使用PyUIC工具转换为.py文件

(c)对密码输入框(lineEdit_2)进行设置

self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password) #设置为密码掩码
self.lineEdit_2.setValidator(QtGui.QIntValidator(10000000,99999999)) #设置为整数且限制位数

完整代码

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

# Form implementation generated from reading ui file 'ui_passpword.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
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(395, 253)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(70, 40, 211, 141))
        self.widget.setObjectName("widget")
        self.gridLayout = QtWidgets.QGridLayout(self.widget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.lineEdit = QtWidgets.QLineEdit(self.widget)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.widget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.gridLayout.addWidget(self.lineEdit_2, 1, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 395, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "用户名:"))
        self.label_2.setText(_translate("MainWindow", "密码:"))

        #为密码栏设置格式
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)  # 设置为密码掩码
        self.lineEdit_2.setValidator(QtGui.QIntValidator(10000000, 99999999))  # 设置为整数且限制位数

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

2.3 TextEdit:多行文本框

显示多行文本内容,当文本内容超出控件的显示范围时将显示垂直滚动条。此外,不仅支持纯文本内容,也支持HTML网页。

实例:设置多行文本和HTML文本的对比显示

#设置纯文本显示
self.textEdit.setPlainText("与失败比起来,我对乏味和平庸的恐惧要严重得多。\n对我而言,很好的事情比糟糕的事情好,而糟糕的事情比平庸的事情好,因为糟糕的事情给生活添加了滋味 ")       
#设置HTML文本显示
self.textEdit_2.setHtml("与失败比起来,我对乏味和平庸的恐惧要严重得多。\n对我而言,<font color='red' size = 12>很好的事情比糟糕的事情好,而糟糕的事情比平庸的事情好,</font>因为糟糕的事情给生活添加了滋味 ")

完整代码:

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

# Form implementation generated from reading ui file 'ui_textedit.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
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(557, 289)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(20, 70, 201, 121))
        self.textEdit.setObjectName("textEdit")
        self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_2.setGeometry(QtCore.QRect(260, 70, 241, 121))
        self.textEdit_2.setObjectName("textEdit_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 557, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

        #设置纯文本显示
        self.textEdit.setPlainText("与失败比起来,我对乏味和平庸的恐惧要严重得多。\n对我而言,很好的事情比糟糕的事情好,而糟糕的事情比平庸的事情好,因为糟糕的事情给生活添加了滋味 ")
        #设置HTML文本显示
        self.textEdit_2.setHtml("与失败比起来,我对乏味和平庸的恐惧要严重得多。\n对我而言,<font color='red' size = 12>很好的事情比糟糕的事情好,而糟糕的事情比平庸的事情好,</font>因为糟糕的事情给生活添加了滋味 ")

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

2.4 SpinBox:整数数字选择控件

默认情况下,SpinBox的取值范围为0~99,步长值为1

也可以自己进行设置:

self.spinBox.setRange(0,200)  #范围为0~200
self.spinBox.setSingleStep(5) #步长为5

实例:对SpinBox控件的范围和步长进行设置,并使用Label控件获取SpinBox中选择的数字(注意自定义GetValue()方法获取值)

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

# Form implementation generated from reading ui file 'ui_spainbox.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
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(557, 289)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.spinBox = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBox.setGeometry(QtCore.QRect(120, 70, 91, 31))
        self.spinBox.setObjectName("spinBox")

        self.spinBox.setRange(0,200)
        self.spinBox.setSingleStep(5) #步长
        self.spinBox.valueChanged.connect(self.GetValue)  #同步数据

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(100, 130, 120, 21))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(250, 130, 101, 21))
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 557, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "当前控件的数值是:"))


    def GetValue(self):  #获取spainbox中的数值
        self.label_2.setText(str(self.spinBox.value()))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

2.5 DoubleSpinaBox:小数数字选择控件

使用同2.4 SpinBox的整数数字选择控件,步长,范围,值获取等,补充一个小数限制位数:

self.doubleSpinBox.setDecimals(3)  #设置保留3位小数

2.6 LCDNumber:液晶数字显示控件

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

# Form implementation generated from reading ui file 'ui_lcdnumber.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
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(557, 289)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(90, 60, 101, 41))
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(220, 70, 113, 20))
        self.lineEdit.setObjectName("lineEdit")

        self.lineEdit.editingFinished.connect(self.getvalue) #输入完数字后按下enter键关联

        self.lcdNumber = QtWidgets.QLCDNumber(self.centralwidget)
        self.lcdNumber.setGeometry(QtCore.QRect(110, 120, 251, 61))
        self.lcdNumber.setLayoutDirection(QtCore.Qt.RightToLeft)
        self.lcdNumber.setSegmentStyle(QtWidgets.QLCDNumber.Filled)
        self.lcdNumber.setObjectName("lcdNumber")

        self.lcdNumber.setDigitCount(6) #限制最大显示6位数
        self.lcdNumber.setMode(QtWidgets.QLCDNumber.Dec) #设置默认以十进制/按需修改
        self.lcdNumber.setSegmentStyle(QtWidgets.QLCDNumber.Flat)  #设置数字显示格式/按需修改

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 557, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "请输入数字:"))


    def getvalue(self): #获得输入的数字并显示
        self.lcdNumber.setProperty('value',self.lineEdit.text())


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

3. 按钮类控件

3.1 PushButton:按钮

PushButton是最常用的按钮控件,前面已有例子使用过,当该控件被单击时看起来的状态像是被按下,然后释放。

实例:为用户登录系统添加“登录”和“退出”按钮,单击“登录”按钮时弹出用户输入的账号和密码,单击“退出”时则关闭当前窗口。

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

# Form implementation generated from reading ui file 'ui_pushbotton.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
from PyQt5.QtGui import QPixmap,QIcon
from PyQt5.QtWidgets import QMessageBox
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(398, 302)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        # self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton = QtWidgets.QPushButton('登录(&D)',self.centralwidget) #设置快捷键为ALT+D

        self.pushButton.setGeometry(QtCore.QRect(80, 210, 85, 33))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(10)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setIcon(QIcon(QPixmap('Chapter5/user.ico'))) #登录图标
        self.pushButton.clicked.connect(self.login)  # 登录按钮关联

        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(210, 210, 85,33))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(10)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setIcon(QIcon(QPixmap('chapter5/exit.ico'))) #退出图标
        self.pushButton_2.clicked.connect(MainWindow.close)  # 退出按钮关联

        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(70, 40, 261, 141))
        self.widget.setObjectName("widget")
        self.gridLayout = QtWidgets.QGridLayout(self.widget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.lineEdit = QtWidgets.QLineEdit(self.widget)
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(12)
        self.lineEdit.setFont(font)
        self.lineEdit.setText("")
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.widget)
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(12)
        self.lineEdit_2.setFont(font)
        self.lineEdit_2.setText("")
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password) #设置密码和格式
        self.lineEdit_2.setValidator(QtGui.QIntValidator(100000,999999))


        self.gridLayout.addWidget(self.lineEdit_2, 1, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 398, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def login(self): #定义登录方法
        QMessageBox.information(MainWindow,"登录信息", "用户名:"+self.lineEdit.text(),"密码:"+self.lineEdit_2.text(),QMessageBox.Ok)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "登录系统"))
        self.pushButton.setText(_translate("MainWindow", "登录"))
        self.pushButton_2.setText(_translate("MainWindow", "退出"))
        self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:14pt;\">用户名:</span></p></body></html>"))
        self.label_2.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:14pt;\">密 码:</span></p></body></html>"))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

3.2 ToolButton:工具按钮

工具按钮显示样式:setToolButtonStle()方法

工具按钮的箭头样式:setArrowType()方法

实例:设计一个向上并将文本显示在文本下方的工具按钮

self.toolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)  #文本显示在图标下
self.toolButton.setArrowType(QtCore.Qt.UpArrow)  #箭头向上

完整代码:

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

# Form implementation generated from reading ui file 'ui_toolbotton.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
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(398, 302)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.toolButton = QtWidgets.QToolButton(self.centralwidget)
        self.toolButton.setGeometry(QtCore.QRect(130, 110, 91, 51))
        
        self.toolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.toolButton.setArrowType(QtCore.Qt.UpArrow)
        
        self.toolButton.setObjectName("toolButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 398, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "欢迎使用"))
        self.toolButton.setText(_translate("MainWindow", "..."))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

3.3 CommandLinkButton:命令链接按钮

不能链接到内容?暂时不知道有什么用,有需要再补充

3.4 RadioButton:单选按钮

RadioButton控件常用的信号有两个:clicked(每次单击单选按钮就会发射),toggled(单选按钮状态改变时发射)。

实例:为3.1登录系统实例添加管理员登录和普通用户登录两种选择

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

# Form implementation generated from reading ui file 'ui_radiobutton.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
from PyQt5.QtGui import QPixmap,QIcon
from PyQt5.QtWidgets import QMessageBox
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(540, 307)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.radioButton = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton.setGeometry(QtCore.QRect(150, 150, 86, 21))
        self.radioButton.setObjectName("radioButton")

        self.radioButton.setChecked(True) #默认选中管理员单选按钮
        self.radioButton.toggled.connect(self.select) #toggled关联

        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(150, 210, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setIcon(QIcon(QPixmap('Chapter5/user.ico')))
        self.pushButton.clicked.connect(self.login)

        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(260, 210, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setIcon(QIcon(QPixmap("Chapter5/exit.ico")))
        self.pushButton_2.clicked.connect(MainWindow.close)  #退出设置

        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(140, 20, 201, 101))
        self.widget.setObjectName("widget")
        self.gridLayout = QtWidgets.QGridLayout(self.widget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.lineEdit = QtWidgets.QLineEdit(self.widget)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.widget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)
        self.lineEdit_2.setValidator(QtGui.QIntValidator(100000,999999))

        self.gridLayout.addWidget(self.lineEdit_2, 1, 1, 1, 1)
        self.radioButton_2 = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton_2.setGeometry(QtCore.QRect(260, 150, 86, 21))
        self.radioButton_2.setObjectName("radioButton_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 540, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def login(self): #定义登录方法
        QMessageBox.information(MainWindow,"登录信息", "用户名:"+self.lineEdit.text(),"密码:"+self.lineEdit_2.text(),QMessageBox.Ok)

    def select(self):  #定义选择的用户身份
        if self.radioButton.isChecked():
            QMessageBox.information(MainWindow,"提示:",'您选择的是 管理员 登录', QMessageBox.Ok)
        elif self.radioButton_2.isChecked():
            QMessageBox.information(MainWindow, "提示:", '您选择的是 普通用户 登录', QMessageBox.Ok)


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.radioButton.setText(_translate("MainWindow", "管理员 "))
        self.pushButton.setText(_translate("MainWindow", "登录"))
        self.pushButton_2.setText(_translate("MainWindow", "退出"))
        self.label.setText(_translate("MainWindow", "用户名:"))
        self.label_2.setText(_translate("MainWindow", "密码:"))
        self.radioButton_2.setText(_translate("MainWindow", "普通用户"))


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

3.5 CheckBox:复选框

实例:设置用户权限,点击设置并显示权限

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

# Form implementation generated from reading ui file 'untitled.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
from PyQt5.QtWidgets import QMessageBox
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(396, 268)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox.setGeometry(QtCore.QRect(60, 60, 91, 31))
        self.checkBox.setObjectName("checkBox")
        self.checkBox_2 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_2.setGeometry(QtCore.QRect(60, 110, 91, 31))
        self.checkBox_2.setObjectName("checkBox_2")
        self.checkBox_3 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_3.setGeometry(QtCore.QRect(60, 160, 91, 31))
        self.checkBox_3.setObjectName("checkBox_3")
        self.checkBox_4 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_4.setGeometry(QtCore.QRect(190, 60, 91, 31))
        self.checkBox_4.setObjectName("checkBox_4")
        self.checkBox_5 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_5.setGeometry(QtCore.QRect(190, 110, 91, 31))
        self.checkBox_5.setObjectName("checkBox_5")
        self.checkBox_6 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_6.setGeometry(QtCore.QRect(190, 160, 91, 31))
        self.checkBox_6.setObjectName("checkBox_6")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(300, 190, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.getvalue)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 396, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def getvalue(self):  # 得到选择情况
        oper = ''       #记录用户权限
        if self.checkBox.isChecked():     #判断是否选中
            oper += self.checkBox.text()  #记录选中权限
        if self.checkBox_2.isChecked():
            oper += "\n" + self.checkBox_2.text()
        if self.checkBox_3.isChecked():
            oper += "\n" + self.checkBox_3.text()
        if self.checkBox_4.isChecked():
            oper += "\n" + self.checkBox_4.text()
        if self.checkBox_5.isChecked():
            oper += "\n" + self.checkBox_5.text()
        if self.checkBox_6.isChecked():
            oper += "\n" + self.checkBox_6.text()
        QMessageBox.information(MainWindow, '提示:', "你的权限如下:\n" + oper, QMessageBox.Ok)


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.checkBox.setText(_translate("MainWindow", "基本信息管理"))
        self.checkBox_2.setText(_translate("MainWindow", "销售管理"))
        self.checkBox_3.setText(_translate("MainWindow", "系统管理"))
        self.checkBox_4.setText(_translate("MainWindow", "进货管理"))
        self.checkBox_5.setText(_translate("MainWindow", "库存管理"))
        self.checkBox_6.setText(_translate("MainWindow", "资金管理"))
        self.pushButton.setText(_translate("MainWindow", "设置"))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

4. 选择列表类控件

4.1 ComboBox:下拉组合框

常用信号:activated(选中一个下拉选项时发射信号),currentIndexChanged(下拉选项的索引发生改变时发射信号)

实例:在下拉列表中选择职位并显示

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

# Form implementation generated from reading ui file 'ui_combobox.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
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(540, 307)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(220, 60, 141, 31))
        self.comboBox.setObjectName("comboBox")

        list = ['总经理','副总经理','人事部总经理','部门经理','普通员工']
        self.comboBox.addItems(list)    #从列表中添加下拉xuanx
        self.comboBox.currentIndexChanged.connect(self.ShowInf)  #选中后关联显示函数

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(123, 62, 81, 31))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(130, 120, 341, 41))
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 540, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def ShowInf(self):
        self.label_2.setText("您当前的职位是"+self.comboBox.currentText())

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "职位选择:"))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

4.2 FontComboBox:字体组合框

在下拉框中显示并选择字体

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

# Form implementation generated from reading ui file 'ui_fontcombobox.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
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(540, 307)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.fontComboBox = QtWidgets.QFontComboBox(self.centralwidget)
        self.fontComboBox.setGeometry(QtCore.QRect(130, 50, 221, 31))
        self.fontComboBox.setObjectName("fontComboBox")

        self.fontComboBox.setFontFilters(QtWidgets.QFontComboBox.AllFonts)  #所有字体
        self.fontComboBox.currentIndexChanged.connect(self.setFont) #字体改变时进行关联


        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(100, 110, 521, 71))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 540, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def setFont(self):  #为显示框设置字体
        print(self.fontComboBox.currentFont())
        self.label.setText(QtGui.QFont(self.fontComboBox.currentFont()))

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", " 每天编程一小时,从菜鸟到大牛"))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

4.3 ListWidget:列表

实例:添加一个LIstWidget控件,显示票房列表(随便打的内容)

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

# Form implementation generated from reading ui file 'ui_listwidget.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
from PyQt5.QtWidgets import QMessageBox
import sys
class Ui_MainWindow(object):
    def setupUi(self, MainWindow, OrderedDict=None):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(540, 307)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget.setGeometry(QtCore.QRect(10, 10, 521, 231))
        self.listWidget.setObjectName("listWidget")

        self.listWidget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection) #列表多选
        self.listWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)   #选中整行
        self.listWidget.setViewMode(QtWidgets.QListView.ListMode)  #列表形式显示
        self.listWidget.setWordWrap(True) #自动换行

        #定义有序字典

        dict = {
            '第一名': "战狼2,2017年上映,票房56.84亿",
            '第二名': "哪吒,2019年上映,票房50.84亿",
            '第三名': "流浪地球,2019年上映,票房48.84亿",
            '第四名': "红海行动,2021年上映,票房46.84亿",
            '第五名': "美人鱼,2021年上映,票房46.80亿",
        }

        for key,value in dict.items():  #遍历字典
            item = QtWidgets.QListWidgetItem(self.listWidget)  #创建列表项
            item.setText(key + ':' + value)  #设置项文本
            item.setToolTip(value)   #设置提示文字

        self.listWidget.itemClicked.connect(self.gettext)


        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 540, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def gettext(self, item):
        if item.isSelected():
            QMessageBox.information(MainWindow,'提示:',"您选择的是"+ item.text(),QMessageBox.Ok)



    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

5. 容器控件

5.1 GroupBox:分组框

主要为其他控件提供分组,并按照控件的分组来细分窗口功能。

5.2 TabWidget:选项卡

可以将窗口设计为多页,以便窗口功能划分为多个部分

实例:选项卡的动态添加和删除

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

# Form implementation generated from reading ui file 'ui_tabwidget.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
from PyQt5.QtWidgets import QMessageBox
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(540, 307)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(20, 10, 511, 191))
        self.tabWidget.setObjectName("tabWidget")
        self.tabWidget.currentChanged.connect(self.gettab)

        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, "")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(160, 220, 81, 31))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.addtab) #关联添加方法


        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(330, 220, 81, 31))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.deltab) #关联删除方法

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 540, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def addtab(self):  #增加选项卡
        self.adtb = QtWidgets.QWidget()
        name = "tab_"+ str(self.tabWidget.count()+1)
        self.adtb.setObjectName(name)
        self.tabWidget.addTab(self.adtb,name)

    def deltab(self):  #删除选项卡
        self.tabWidget.removeTab(self.tabWidget.currentIndex())


    def gettab(self, currentIndx):  # 获取当前索引
        QMessageBox.information(MainWindow, "提示:", "您选择了" + self.tabWidget.tabText(currentIndx) +
                                "选项卡,索引为:" + str(self.tabWidget.currentIndex()), QMessageBox.Ok)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2"))
        self.pushButton.setText(_translate("MainWindow", "添加"))
        self.pushButton_2.setText(_translate("MainWindow", "删除"))


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())

5.3 ToolBox:工具盒

可提供一种列状的层叠选项卡,如QQ抽屉效果(略)

6. 时间和日期类控件

from PyQt5 import QtCore
datatime = QtCore.QDateTime.currentDateTime()  #获取当前系统的日期和时间

实例:在窗口中添加一个CalendarWidget控件,并定义一个方法获取在控件中选择的日期,以“年-月-日”的形式显示在提示框

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

# Form implementation generated from reading ui file 'ui_canlendarwidget.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
from PyQt5.QtWidgets import QMessageBox
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(540, 307)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.calendarWidget = QtWidgets.QCalendarWidget(self.centralwidget)
        self.calendarWidget.setGeometry(QtCore.QRect(100, 10, 312, 218))
        self.calendarWidget.setObjectName("calendarWidget")
        self.calendarWidget.setSelectedDate(QtCore.QDate(2024,1,5))  #设置默认选中的日期
        self.calendarWidget.setMinimumDate(QtCore.QDate(2000,1,1))   #设置最小日期
        self.calendarWidget.setMaximumDate(QtCore.QDate(9999,1,1))  #设置最大日期
        self.calendarWidget.setFirstDayOfWeek(QtCore.Qt.Monday)   #周一为第一天
        self.calendarWidget.setGridVisible(True)   #设置网格线可见
        self.calendarWidget.setSelectionMode(QtWidgets.QCalendarWidget.SingleSelection) #可以单选日期
        self.calendarWidget.setHorizontalHeaderFormat(QtWidgets.QCalendarWidget.ShortDayNames) #水平表头为简短形式 “周一”
        self.calendarWidget.setVerticalHeaderFormat(QtWidgets.QCalendarWidget.ISOWeekNumbers) #垂直表头为周数
        self.calendarWidget.setNavigationBarVisible(True) #设置显示导航栏
        self.calendarWidget.setDateEditEnabled(True) #设置日期可编辑
        self.calendarWidget.selectionChanged.connect(self.getdata)  #日期选择变化时关联显示


        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 540, 27))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def getdata(self):  # 获取所选时间
        data = self.calendarWidget.selectedDate()  # 获取当前选择的QDate对象
        year = data.year()
        month = data.month()
        day = data.day()
        QMessageBox.information(MainWindow, "提示", str(year) + "-" + str(month) + "-" + str(day), QMessageBox.Ok)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    app.exit(app.exec_())
文章来源:https://blog.csdn.net/weixin_47622017/article/details/135407888
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。