PyQt5

作者: lk_erzanml | 来源:发表于2022-11-13 20:52 被阅读0次

    [toc]

    教程地址

    安装:
    https://www.cnblogs.com/ldym/p/16031455.html

    基本使用:
    https://doc.itprojects.cn/0001.zhishi/python.0008.pyqt5rumen/index.html#/09.build

    详细教程:
    链接:https://pan.baidu.com/s/1jONVVDfGmpqVeTbp0nI0JQ?pwd=gsiq
    提取码:gsiq

    博客教程:
    https://www.cnblogs.com/linyfeng/tag/pyqt/

    某人学习笔记:
    https://www.yuque.com/kd_huhu/khxob0/utg8t9

    PyQt5窗口样式和绘图

    #设置窗口风格
    
    import sys
    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5 import QtCore
    
    class AppWidget(QWidget):
        def __init__(self,parent=None):
            super().__init__(parent)
    
            horizontalLayout =QHBoxLayout() #水平布局
    
    
            self.styleLabel = QLabel("Set Style:")
            self.styleComboBox = QComboBox()
            print(QStyleFactory.keys())#默认风格,系统级别,每个系统不是特别一样
            self.styleComboBox.addItems(QStyleFactory.keys())
            # 选择当前窗口风格
            index = self.styleComboBox.findText(QApplication.style().objectName(),QtCore.Qt.MatchFixedString)
            # 设置当前窗口风格,index是int
            self.styleComboBox.setCurrentIndex(index)
            #通过combox控件选择窗口风格
            self.styleComboBox.activated[str].connect(self.handleStyleChanged)
    
            horizontalLayout.addWidget(self.styleLabel)
            horizontalLayout.addWidget(self.styleComboBox)
            
            self.setLayout(horizontalLayout)
    
        def handleStyleChanged(self,style):
            QApplication.setStyle(style)
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        wid = AppWidget()
        wid.show()
        sys.exit(app.exec_())
        
    
    # 设置窗口样式
    
    from PyQt5.QtCore import *
    import sys
    from PyQt5.QtWidgets import *
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.resize(500,260)
            self.setWindowTitle("设置窗口样式例子")
            #设置无边框窗口样式
            self.setWindowFlags(Qt.FramelessWindowHint)
            
            app=QApplication.instance() #获取当前app
            print(app.dicts)
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        app.dicts={"a":100}  #通过全局给app传一个参数,其他窗体可以共用
        win=MainWindow()
        win.show()
        sys.exit(app.exec_())
        
    
    # 使用自定义的无边框窗口
    
    import sys
    from PyQt5.QtWidgets import QMainWindow,QApplication
    from PyQt5.QtCore import Qt
    
    class MyWindow(QMainWindow):
    
        def __init__(self,parent=None):
            super().__init__(parent)
    
            self.setWindowFlags(Qt.FramelessWindowHint)
    
            #设置窗口背景颜色
            self.setStyleSheet('''background-color:blue;''')
    
            #得到桌面控件
            desktop=QApplication.desktop()
    
            #得到屏幕尺寸
            rect=desktop.availableGeometry()
            print(rect)
    
            # 设置窗口尺寸
            self.setGeometry(rect)
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        window = MyWindow()
        window.show()
        sys.exit(app.exec_())
        
    
    # 画图
    import sys
    from PyQt5.QtWidgets import QApplication,QWidget
    from PyQt5.QtGui import QPainter,QPixmap
    from PyQt5.QtCore import Qt,QPoint
    
    class Winform(QWidget):
    
        def __init__(self,parent=None):
            super().__init__(parent)
            self.setWindowTitle("绘图例子")
    
            #初始化两个位置
            self.lastPoint = QPoint()#开始位置
            self.endPoint = QPoint()#结束位置
    
            self.initUi()
    
        def initUi(self):
            self.resize(600,500)
            self.pix = QPixmap(600,500)#画布
            self.pix.fill(Qt.white)
    
        def paintEvent(self,e):
            pp=QPainter(self.pix)
            pp.drawLine(self.lastPoint,self.endPoint)#画直线
            self.lastPoint=self.endPoint#每次画完了都把结束点复制给开始点
            painter = QPainter(self)
            painter.drawPixmap(0,0,self.pix)
    
        def mousePressEvent(self,e):
            if e.button()==Qt.LeftButton:
                self.lastPoint=e.pos()#按下鼠标键,开始位置是鼠标位置
                self.endPoint=self.lastPoint#结束位置是开始位置,相当于先画一个点
    
        def mouseMoveEvent(self,e):
            if e.buttons():
    
                self.endPoint=e.pos()#鼠标移动,结束点被赋值成鼠标垫
    
                self.update()#self.update才开始调用paintEvent事件
    
        def mouseReleaseEvent(self,e):
            if e.button()==Qt.LeftButton:
    
                self.endPoint=e.pos()#鼠标释放,结束点被赋值成鼠标位置点
    
                self.update()
    
    if __name__ == "__main__":
    
        app=QApplication(sys.argv)
        form = Winform()
        form.show()
        sys.exit(app.exec_())
    
    
    # 绘制矩形,出现重影
    
    import sys
    from PyQt5.QtWidgets import QMainWindow,QApplication,QWidget
    from PyQt5.QtCore import Qt,QPoint
    from PyQt5.QtGui import QPainter,QPixmap
    
    class MyWindow(QWidget):
    
        def __init__(self,parent=None):
            super().__init__(parent)
    
            self.lastPoint=QPoint()
            self.endPoint=QPoint()
            self.initUi()
    
        def initUi(self):
            self.resize(600,500)
            self.pix=QPixmap(600,500)#画布
            self.pix.fill(Qt.white)
    
        def paintEvent(self,e):
    
            x=self.lastPoint.x()
            y=self.lastPoint.y()
            w=self.endPoint.x()-x
            h=self.endPoint.y()-y
    
            pp=QPainter(self.pix)#画笔
            pp.drawRect(x,y,w,h)
            painter = QPainter(self)
            painter.drawPixmap(0,0,self.pix)
    
        def mousePressEvent(self,e):
            if e.button()==Qt.LeftButton:
                self.lastPoint=e.pos()
                self.endPoint=self.lastPoint
    
        def mouseMoveEvent(self,e):
            if e.buttons():
                self.endPoint=e.pos()
                self.update()
    
        def mouseReleaseEvent(self,e):
            if e.button()==Qt.LeftButton:
                self.endPoint=e.pos()
                self.update()
    
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        window = MyWindow()
        window.show()
        sys.exit(app.exec_())
    

    PyQt5_QSS样式

    # 7种选择器
    from PyQt5.QtWidgets import *
    import sys
    
    class WindowDemo(QWidget):
    
        def __init__(self):
            super().__init__()
    
            btn1=QPushButton(self)
            btn1.setText("按钮")
            btn1.setObjectName("btn11")
    
            btn2=QPushButton(self)
            btn2.setText("按钮2")
            btn2.setProperty('xiaolifeidao',"lixunhuan")
            label = QLabel(self)
            label.setText("测试类选择器")
            label2=CeshiButton(self)
            label2.setText("子类")
    
            vbox=QVBoxLayout()
            vbox.addWidget(btn1)
            vbox.addWidget(btn2)
            vbox.addWidget(label)
            vbox.addWidget(label2)
    
    
    
            self.setLayout(vbox)
    
            self.setWindowTitle("QSS样式")
    
    class CeshiButton(QLabel):#测试类选择器
        def __init__(self,parent=None):
            super().__init__(parent)
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        win=WindowDemo()
    
        # QpushButton,QlineEdit{color:red}<==>QpushButton{color:red}QLineEdit{color:red}
        # 继承会继承QSS样式
        # 1.通配选择,*
        # qssStyle="""
        #     *{
        #         background-color:red
        #     }
        # """
        # 2.类型选择器QPushButton;继承它的子类都会被设置样式
        # qssStyle = """
        #         QPushButton{
        #             background-color:red
        #         }
        #     """
        # 3.属性选择器
        # qssStyle = """
        #             QPushButton[xiaolifeidao='lixunhuan']{
        #                 background-color:red
        #             }
        #         """
        # 4.类选择器 .QPushButton;类选择器只匹配本类,不涉及继承
        # qssStyle = """
        #                 QWidget>.QLabel{
        #                     color:red
        #                 }
        #             """
        #5.id选择器
        qssStyle = """
                            #btn11{
                                color:red
                            }
                        """
        #6.后代选择器QDialog QPushButton
        #7.子选择器QDialog>QPushButton
        win.setStyleSheet(qssStyle)
        win.show()
        sys.exit(app.exec_())
    
    # 子控件
    
    import sys
    from PyQt5.QtWidgets import *
    
    class Winform(QWidget):
    
        def __init__(self,parent=None):
            super().__init__(parent)
    
            combo = QComboBox(self)
            combo.setObjectName("xxxx")
            combo.addItem("window")
            combo.addItem("Ubuntu")
            combo.addItem("red hat")
    
            combo.move(50,50)
            qssstyle="""
                QComboBox::drop-down{
                    image:url(./123.png)
                }
            """
            combo.setStyleSheet(qssstyle)
    
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        form=Winform()
        form.show()
        sys.exit(app.exec_())
    
    # 伪状态
    
    import sys
    from PyQt5.QtWidgets import *
    
    class Winform(QWidget):
    
        def __init__(self,parent=None):
            super().__init__(parent)
    
            combo = QComboBox(self)
            combo.setObjectName("xxxx")
            combo.addItem("window")
            combo.addItem("Ubuntu")
            combo.addItem("red hat")
    
            combo.move(50,50)
            qssstyle="""
                QComboBox:hover{
                    background:red;
                }
            """
            combo.setStyleSheet(qssstyle)
    
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        form=Winform()
        form.show()
        sys.exit(app.exec_())
    
    # 伪状态还有:
    :checked 被选中
    :unchecked 未被选中
    :hover 鼠标略过
    :pressed 按键被按下
    :focus 聚焦
    :disable 失效
    :enable 有效
    
    # 导入别人写的样式,比如卸载pip install qdarkstyle
    import logging
    import sys
    from PyQt5 import QtWidgets,QtCore
    import qdarkstyle
    
    
    class Me(QtWidgets.QMainWindow):
    
        def __init__(self):
            super().__init__()
            self.button=QtWidgets.QPushButton("nihao",self)
    if __name__=="__main__":
        app=QtWidgets.QApplication(sys.argv)
        app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())#导入
        w=Me()
        w.show()
        sys.exit(app.exec_())
    
    
    # 设置背景颜色的三种方式
    
    # 1.QSS
    # 2.QPlette
    # 3.QPainter
    
    import sys
    from PyQt5.QtWidgets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    
    app = QApplication(sys.argv)
    win = QMainWindow()
    win.setWindowTitle("背景图片")
    win.resize(350,250)
    win.setObjectName("MainWindow")
    # win.setStyleSheet("#MainWindow{background:url(./123.png)}")
    # palette=QPalette()
    # palette.setBrush(QPalette.Background,QBrush(QPixmap('./123.png')))
    # win.setPalette(palette)
    
    win.show()
    sys.exit(app.exec())
    
    # 缩放图片
    
    from PyQt5.QtWidgets import QApplication,QLabel,QWidget,QVBoxLayout
    from PyQt5.QtGui import QImage,QPixmap
    from PyQt5.QtCore import Qt
    import sys
    
    class ScaleImage(QWidget):
    
        def __init__(self):
            super().__init__()
            self.setWindowTitle("缩放图片大小的例子")
            filename='./123.png'
    
            img=QImage(filename)
    
            label1=QLabel(self)
            label1.setFixedWidth(200)
            label1.setFixedHeight(200)
    
            #ignoreaspectratio是忽略长宽比;smoothtransformation是让图像尽量平滑显示
            result = img.scaled(label1.width(),label1.height(),Qt.IgnoreAspectRatio,Qt.SmoothTransformation)
    
            label1.setPixmap(QPixmap.fromImage(result))
    
            vbox=QVBoxLayout()
    
            vbox.addWidget(label1)
    
            self.setLayout(vbox)
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
    
        win = ScaleImage()
        win.show()
    
        sys.exit(app.exec_())
    
    # 装载QSS文件
    
    import sys
    from PyQt5.QtWidgets import *
    
    class MainWindow(QMainWindow):
    
        def __init__(self,parent=None):
            super().__init__(parent)
    
            self.resize(477,258)
    
            self.setWindowTitle("加载QSS文件")
    
            btn=QPushButton()
    
            btn.setText("装载QSS文件")
    
            btn.setToolTip("提示文本")
    
            vbox=QVBoxLayout()
    
            vbox.addWidget(btn)
    
            btn.clicked.connect(self.onClick)
    
            widget = QWidget(self)
    
            self.setCentralWidget(widget)
    
            widget.setLayout(vbox)
    
        def onClick(self):
            styleFile='./style.qss'
            with open(styleFile,'r') as f:
                self.setStyleSheet(f.read())
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
    
        win=MainWindow()
        win.show()
    
        sys.exit(app.exec_())
        
    

    PyQt5配合matplotlib

    # PyQt5配合Matplotlib
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.figure import Figure
    import matplotlib.pyplot as plt
    from PyQt5.QtWidgets import *
    import math
    from PyQt5 import QtCore
    
    
    class MyMplCanvas(FigureCanvas):
    
        def __init__(self,parent=None,width=5,height=4,dpi=100):
            plt.rcParams['font.family']=['SimHei']
            plt.rcParams['axes.unicode_minus']=False
    
            self.fig=Figure(figsize=(width,height),dpi=dpi)
    
            self.axes=self.fig.add_subplot(111)
    
    
            FigureCanvas.__init__(self,self.fig)
    
            self.setParent(parent)
    
            FigureCanvas.setSizePolicy(self,QSizePolicy.Expanding,QSizePolicy.Expanding)
    
            FigureCanvas.updateGeometry(self)
    
        def start_static_plot(self):
            self.fig.suptitle("测试静态图")
    
            t=[i for i in range(10)]
            s=[i*2 for i in range(10)]
    
            self.axes.plot(t,s)
    
            self.axes.set_ylabel("静态图:Y轴")
            self.axes.set_xlabel("静态图:X轴")
            self.axes.grid(True)
    
        def start_dynamic_plot(self,*args,**kwargs):
    
            timer=QtCore.QTimer(self)
            timer.timeout.connect(self.update_figure)
    
            timer.start(1000)
    
        def update_figure(self):
            self.fig.suptitle("测试静态图")
            import random
            l=[random.randint(0,10) for i in range(100)]
            self.axes.plot([i for i in range(100)],l,'r')
    
            self.axes.set_ylabel("动态图:Y轴")
            self.axes.set_xlabel("动态图:X轴")
    
            self.axes.grid(True)
    
            self.draw()
    
    class MatplotlibWidget(QWidget):
    
        def __init__(self,parent=None):
            super().__init__()
            self.initUi()
    
        def initUi(self):
            self.layout=QVBoxLayout(self)
    
            self.mpl=MyMplCanvas(self,width=5,height=4,dpi=100)
    
            self.layout.addWidget(self.mpl)
    
    
    if __name__=="__main__":
        import sys
        app=QApplication(sys.argv)
        ui=MatplotlibWidget()
        # ui.mpl.start_static_plot()  #静态图
        ui.mpl.start_dynamic_plot()   #动态图
        ui.show()
    
        sys.exit(app.exec_())
    
    

    信号与槽

    # 内置信号与槽
    
    from PyQt5.QtWidgets import *
    import sys
    
    class SigalSlotDemo(QWidget):
    
        def __init__(self):
            super().__init__()
            self.initUI()
    
        def onClick(self):
            self.btn.setText("信号已经发出")
            self.btn.setStyleSheet("QPushButton{color:red;}")
    
        def initUI(self):
            self.setGeometry(300,300,500,400)
            self.btn = QPushButton("我的按钮",self)
            self.btn.clicked.connect(self.onClick)
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
    
        gui=SigalSlotDemo()
    
        gui.show()
    
        sys.exit(app.exec_())
    
    
    # 自定义信号
    
    """
    创建信号
    连接信号和槽函数
    在适当的时候发射信号
    """
    
    from PyQt5.QtCore import *
    
    class MyTypeSignal(QObject):
    
        sendmsg = pyqtSignal(object)
    
        sendmsg1 = pyqtSignal(str,int,int)
    
        def run(self):
            self.sendmsg.emit("Hello PyQt5")
    
        def run1(self):
            self.sendmsg1.emit("hello",3,4)
    
    class MySlot(QObject):
        def get(self,msg):
            print("信息:"+msg)
        def get1(self,msg,a,b):
            print(msg)
            print(a+b)
    
    if __name__=="__main__":
        send=MyTypeSignal()
        slot = MySlot()
    
        send.sendmsg.connect(slot.get)
        send.sendmsg1.connect(slot.get1)
    
        send.run()
        send.run1()
    
        send.sendmsg.disconnect(slot.get)
    
        send.run()
    
    # 内置信号和内置槽
    
    from PyQt5.QtWidgets import *
    import sys
    
    class Winform(QWidget):
        def __init__(self,parent=None):
    
            super().__init__(parent)
    
            self.resize(330,50)
    
            btn=QPushButton('关闭',self)
            btn.clicked.connect(self.close)
    
    if __name__=='__main__':
        app=QApplication(sys.argv)
    
        win = Winform()
    
        win.show()
    
        sys.exit(app.exec_())
    
    # 添加多个信号
    
    from PyQt5.QtCore import *
    
    class MultiSignal(QObject):
        signal1 = pyqtSignal()
        signal2 = pyqtSignal(int)
        signal3 = pyqtSignal(int,str)
        signal4 = pyqtSignal(list)
        signal5 = pyqtSignal(dict)
        signal6 = pyqtSignal([int,str],[str])#重载
    
        def __init__(self):
            super().__init__()
            self.signal1.connect(self.signalCall1)
            self.signal2.connect(self.signalCall2)
            self.signal3.connect(self.signalCall3)
            self.signal4.connect(self.signalCall4)
            self.signal5.connect(self.signalCall5)
            # 重载,对齐函数就可以
            self.signal6[str].connect(self.signalCall60verload)
            self.signal6[int,str].connect(self.signalCall6)
    
            #触发信号
    
            self.signal1.emit()
            self.signal2.emit(10)
            self.signal3.emit(1,"hello world")
            self.signal4.emit([1,2,3,4])
            self.signal5.emit({"name":"Bill","age":30})
    
            self.signal6[str].emit("test")
            self.signal6[int,str].emit(100,"mytest")
    
        # 定义槽
        def signalCall1(self):
            print("signal1 emit")
    
        def signalCall2(self,val):
            print("signal2 emit",val)
    
        def signalCall3(self,val,text):
            print("signal3 emit",val,text)
    
        def signalCall4(self,val):
            print("signal4 emit",val)
    
        def signalCall5(self,val):
            print("signal5 emit",val)
    
        def signalCall6(self,val,text):
            print("signal6 emit",val,text)
    
        def signalCall60verload(self,val):
            print("signal6 overload emit",val)
    
    MultiSignal()
    
    
    # 信号与槽多对多关系
    
    '''
    多个信号可以和多个槽绑定,但是绑定的参数必须匹配
    单个信号可以绑定多个槽,触发时候按照绑定顺序执行。
    信号可以和信号关联。一个信号关联另一个信号,再出发的时候本质是触发了关联信号。
    '''
    
    from PyQt5.QtCore import *
    
    class NNSignal(QObject):
        signal1 = pyqtSignal()
        signal2 = pyqtSignal(int)
        signal3 = pyqtSignal()
    
        def __init__(self):
            super().__init__()
            self.signal1.connect(self.call1)
            self.signal1.connect(self.call11)
            self.signal3.connect(self.call1)
    
            self.signal1.emit() #按顺序执行了两次
            self.signal3.emit()
    
            self.signal2.connect(self.signal1)#信号连接信号
            self.signal2.emit(2)
    
        def call1(self):
            print("call1 emit")
    
        def call11(self):
            print("call11 emit")
    
        def call2(self,val):
            print("call2 emit:",val)
    
    if __name__=="__main__":
        NNSignal()
    
    # 多线程更新UI数据
    
    '''
    要发送的地方,建立一个信号,然后发送数据;
    接收的地方,绑定槽,槽函数在接收的地方就能收到数据
    '''
    
    from PyQt5.QtCore import QThread,pyqtSignal,QDateTime
    from PyQt5.QtWidgets import QApplication,QDialog,QLineEdit
    import time
    import sys
    
    class BackendThread(QThread):
    
        update_date = pyqtSignal(str)
    
        def run(self):
            while True:
                data = QDateTime.currentDateTime()
                currentTime= data.toString("yyy-MM-dd hh:mm:ss")
                self.update_date.emit(str(currentTime))
                time.sleep(1)
    
    class ThreadUpdateUI(QDialog):
    
        def __init__(self):
            QDialog.__init__(self)
            self.resize(400,100)
    
            self.input=QLineEdit(self)
    
            self.input.resize(400,100)
    
            self.initUI()
    
        def initUI(self):
            self.backend = BackendThread()
            self.backend.update_date.connect(self.handleDisplay)
            self.backend.start()
    
        def handleDisplay(self,data):
            self.input.setText(data)
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        example = ThreadUpdateUI()
        example.show()
        sys.exit(app.exec_())
        
    
    # 默认信号是没有参数的,可以通过lambda绑定参数
    
    from PyQt5.QtWidgets import *
    
    import sys
    
    class LambdaSlotArg(QMainWindow):
    
        def __init__(self):
            super().__init__()
    
            button1 = QPushButton("按钮1")
    
            button2 = QPushButton("按钮2")
    
            ok=100
    
            button1.clicked.connect(lambda: self.onButtonClick(10,ok))
    
            button2.clicked.connect(lambda:self.onButtonClick(ok,-20))
    
            button1.clicked.connect(lambda:QMessageBox.information(self,"结果","单击了button1"))
    
            layout=QHBoxLayout()
    
            layout.addWidget(button1)
            layout.addWidget(button2)
    
            mainFrame=QWidget()
            mainFrame.setLayout(layout)
            self.setCentralWidget(mainFrame
                                  )
    
        def onButtonClick(self,m,n):
            print("m+n=",m+n)
            QMessageBox.information(self,"结果",str(m+n))
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        form =LambdaSlotArg()
        form.show()
    
        sys.exit(app.exec_())
        
    
    # 1.直接调用控件获取控件的数据
    import sys
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    
    class DateDialog(QDialog):
        def __init__(self,parent=None):
    
            super().__init__(parent)
    
            self.setWindowTitle("DateDialog")
    
            layout= QVBoxLayout(self)
            self.datetime =QDateTimeEdit(self)
            self.datetime.setCalendarPopup(True)
            self.datetime.setDateTime(QDateTime.currentDateTime())
    
            layout.addWidget(self.datetime)
    
            buttons = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel,Qt.Horizontal,self)
    
            buttons.accepted.connect(self.accept)
            buttons.rejected.connect(self.reject)
    
            layout.addWidget(buttons)
    
        def dateTime(self):
            return self.datetime.dateTime()
    
        @staticmethod
        def getDateTime(parent=None):
            dialog=DateDialog(parent)
            result=dialog.dateTime()
            date=dialog.dateTime()
            return (date.date(),date.time(),result==QDialog.Accepted)
    
    class MultiWindow1(QWidget):
    
        def __init__(self):
            super().__init__()
            self.setWindowTitle("多窗口交互:不适用信号与槽")
            self.lineEdit=QLineEdit(self)
    
            self.button1 = QPushButton("弹出对话框1")
    
            self.button1.clicked.connect(self.onButton1Click)
    
            self.button2 = QPushButton("弹出对话框2")
    
            self.button2.clicked.connect(self.onButton2Click)
    
            gridLayout = QGridLayout()
    
            gridLayout.addWidget(self.lineEdit)
            gridLayout.addWidget(self.button1)
            gridLayout.addWidget(self.button2)
    
            self.setLayout(gridLayout)
    
        def onButton1Click(self):
            dialog=DateDialog(self)
            result=dialog.exec()
            date=dialog.dateTime()
            self.lineEdit.setText(date.date().toString())
            dialog.destroy
    
        def onButton2Click(self):
            date,time,result = DateDialog.getDateTime(self)
            self.lineEdit.setText(date.toString())
            if result == QDialog.Accepted:
                print("点击了确定按钮")
            else:
                print("点击了取消按钮")
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
    
        form = MultiWindow1()
    
        form.show()
    
        sys.exit(app.exec_())
    
    
    # 通过信号传递参数
    import sys
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    
    class DateDialog(QDialog):
        Signal_OneParameter=pyqtSignal(str)
        def __init__(self,parent=None):
    
            super().__init__(parent)
    
            layout= QVBoxLayout(self)
    
            self.label=QLabel(self)
            self.label.setText("前者发射内置信号\n后者发射自定义信号")
            self.datetime_inner =QDateTimeEdit(self)
            self.datetime_inner.setCalendarPopup(True)
            self.datetime_inner.setDateTime(QDateTime.currentDateTime())
            self.datetime_emit = QDateTimeEdit(self)
            self.datetime_emit.setCalendarPopup(True)
            self.datetime_emit.setDateTime(QDateTime.currentDateTime())
    
            layout.addWidget(self.label)
            layout.addWidget(self.datetime_inner)
            layout.addWidget(self.datetime_emit)
    
            buttons = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel,Qt.Horizontal,self)
    
            buttons.accepted.connect(self.accept)
            buttons.rejected.connect(self.reject)
    
            layout.addWidget(buttons)
            self.datetime_emit.dateTimeChanged.connect(self.emit_signal)
    
    
        def emit_signal(self):
            date_str = self.datetime_emit.dateTime().toString()
            self.Signal_OneParameter.emit(date_str)
    
        @staticmethod
        def getDateTime(parent=None):
            dialog=DateDialog(parent)
            result=dialog.dateTime()
            date=dialog.dateTime()
            return (date.date(),date.time(),result==QDialog.Accepted)
    
    class MultiWindow1(QWidget):
    
        def __init__(self):
            super().__init__()
            self.setWindowTitle("多窗口交互:信号与槽")
            self.open_btn=QPushButton("获取时间")
    
            self.lineEdit_inner=QLineEdit(self)
            self.lineEdit_emit=QLineEdit(self)
    
            self.open_btn.clicked.connect(self.openDialog)
    
            gridLayout = QGridLayout()
    
            gridLayout.addWidget(self.lineEdit_inner)
            gridLayout.addWidget(self.lineEdit_emit)
            gridLayout.addWidget(self.open_btn)
    
            self.setLayout(gridLayout)
    
        def openDialog(self):
            dialog=DateDialog(self)
            dialog.datetime_inner.dateTimeChanged.connect(self.deal_inner_slot)
            dialog.Signal_OneParameter.connect(self.deal_emit_slot)
            dialog.show()
    
        def deal_inner_slot(self,date):
            self.lineEdit_inner.setText(date.toString())
    
        def deal_emit_slot(self,datestr):
            self.lineEdit_emit.setText(datestr)
    if __name__=="__main__":
        app=QApplication(sys.argv)
    
        form = MultiWindow1()
    
        form.show()
    
        sys.exit(app.exec_())
    
    
    

    定时器

    # 定时器
    
    from PyQt5.QtWidgets import QGridLayout,QWidget,QPushButton,QApplication,QLabel
    from PyQt5.QtCore import QTimer,QDateTime
    import sys
    
    class ShowTime(QWidget):
        def __init__(self,parent=None):
    
            super().__init__(parent)
            self.setWindowTitle("动态显示当前时间")
    
            self.label = QLabel("显示当前时间")
            self.startbtn=QPushButton("开始")
            self.endbtn=QPushButton("结束")
    
            layout=QGridLayout()
            self.timer = QTimer()
    
            self.timer.timeout.connect(self.showTime)
    
            layout.addWidget(self.label,0,0,1,2)
            layout.addWidget(self.startbtn,1,0)
            layout.addWidget(self.endbtn,1,1)
    
            self.startbtn.clicked.connect(self.startTime)
            self.endbtn.clicked.connect(self.endTimer)
    
            self.setLayout(layout)
    
            self.resize(400,300)
    
        def showTime(self):
            time=QDateTime.currentDateTime()
    
            timedisplay=time.toString('yyyy-MM-dd hh:mm:ss ddd')
            self.label.setText(timedisplay)
    
        def startTime(self):
            self.timer.start(1000)
            self.startbtn.setEnabled(False)
            self.endbtn.setEnabled(True)
    
        def endTimer(self):
            self.timer.stop()
            self.startbtn.setEnabled(True)
            self.endbtn.setEnabled(False)
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        form=ShowTime()
        form.show()
        sys.exit(app.exec_())
    
    
    # 一次性定时器
    
    import sys
    from PyQt5.QtWidgets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    
    app=QApplication(sys.argv)
    
    label=QLabel("<font color=red size=140><b>Hello World,窗口在5s自动关闭!</b></font>")
    label.setWindowFlags(Qt.SplashScreen|Qt.FramelessWindowHint)
    label.show()
    
    QTimer.singleShot(5000,app.quit)
    
    sys.exit(app.exec_())
    
    

    线程

    # 线程
    
    import sys
    
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    
    sec=0
    
    class WorkThread(QThread):
    
        timer = pyqtSignal()
    
        end= pyqtSignal()
    
        def run(self):
            while True:
                self.sleep(1)
                if sec==5:
                    self.end.emit()
                    break
                self.timer.emit()
    
    class Counter(QWidget):
    
        def __init__(self,parent=None):
    
            super().__init__(parent)
    
            self.setWindowTitle("使用线程编写计数器")
    
            self.resize(300,120)
    
            layout=QVBoxLayout()
    
            self.lcdNumber=QLCDNumber()
            layout.addWidget(self.lcdNumber)
            button = QPushButton("开始计数")
    
            layout.addWidget(button)
    
            self.workThread = WorkThread()
            self.workThread.timer.connect(self.countTime)
            self.workThread.end.connect(self.end)
            button.clicked.connect(self.work)
    
            self.setLayout(layout)
    
        def countTime(self):
            global sec
            sec+=1
            self.lcdNumber.display(sec)
    
        def end(self):
            QMessageBox.information(self,"消息",'计数结束',QMessageBox.Ok)
    
        def work(self):
            self.workThread.start()
    
    if __name__=="__main__":
        app=QApplication(sys.argv)
        form = Counter()
        form.show()
        sys.exit(app.exec_())
        
    

    相关文章

      网友评论

          本文标题:PyQt5

          本文链接:https://www.haomeiwen.com/subject/nyjkxdtx.html