pyqt5学习笔记

作者:泥泥
发布于:2020年7月27日 16:36
更新于:2020年9月6日 15:28

pyqt5开发学习笔记!可能会是篇很长的记录!学习的过程总是痛苦的.迈过去了.一切都开朗...

 

一.QLineEdit控件

1.1.给窗口和控件添加提示信息

import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QMainWindow, QToolTip, QWidget, QHBoxLayout
from PyQt5.QtGui import QFont


class ToolTipForm(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        QToolTip.setFont(QFont("sansSerif", 12))
        self.setToolTip("这是一个窗口提示文字")
        self.setGeometry(300, 300, 400, 400)
        self.setWindowTitle("这是窗口的标题")

        self.button1 = QPushButton('我的按钮')
        self.button1.setToolTip("这是按钮上的提示")

        layout = QHBoxLayout()
        layout.addWidget(self.button1)

        mainFrame = QWidget()
        mainFrame.setLayout(layout)
        self.setCentralWidget(mainFrame)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = ToolTipForm()
    main.show()
    sys.exit(app.exec_())

 

 1.2.Qlable使用

代码如下

import sys
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QToolTip, QWidget, QVBoxLayout
from PyQt5.QtGui import QPixmap, QFont, QPalette
from PyQt5.QtCore import Qt


class QlabelDemon(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        labe1 = QLabel(self)
        labe2 = QLabel(self)
        labe3 = QLabel(self)
        labe4 = QLabel(self)

        labe1.setText("<font color='yello'>这是一个文本标签</font>")
        labe1.setAutoFillBackground(True)
        palette = QPalette()
        palette.setColor(QPalette.Window, Qt.blue)
        labe1.setPalette(palette)
        labe1.setAlignment(Qt.AlignCenter)

        labe2.setText("<a href='#'>欢迎走入PYTHON GUI</a>")
        labe2.setAlignment(Qt.AlignCenter)

        labe3.setToolTip("这是个图片标签")
        labe3.setPixmap(QPixmap('.\image\logo.png'))

        labe4.setText("<a href='https://www.ttgame.net'>天心数据</a>")
        labe4.setOpenExternalLinks(True)
        labe4.setAlignment(Qt.AlignRight)
        labe4.setToolTip("这是个超级链接")

        labe2.linkHovered.connect(self.linkHover)
        labe4.linkActivated.connect(self.linkClick)

        qv = QVBoxLayout()
        qv.addWidget(labe1)
        qv.addWidget(labe2)
        qv.addWidget(labe3)
        qv.addWidget(labe4)

        self.setLayout(qv)
        self.setWindowTitle("测试lable和事件")
    def linkHover(self):
        print("当鼠标滑过lable2时触发的事件")

    def linkClick(self):
        print("当鼠标点击lable4时触发的事件")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QlabelDemon()
    main.show()
    sys.exit(app.exec_())

 

1.3.Qlabel设置伙伴关系和快捷键 

import sys
from PyQt5.QtWidgets import *


class QlabelBuddy(QDialog):
    def __init__(self):
        super().__init__()
        self.initUI()


    def initUI(self):
        self.setWindowTitle("测试lable伙伴")

        namelabel = QLabel('&Name', self)
        nameLineEditor = QLineEdit(self)
        namelabel.setBuddy(nameLineEditor)

        pwdlabel = QLabel('&Password', self)
        pwdLineEditor = QLineEdit(self)
        pwdlabel.setBuddy(pwdLineEditor)

        btnOK = QPushButton("&OK")
        btnCancel = QPushButton("&Cancel")

        mainLayout = QGridLayout(self)
        mainLayout.addWidget(namelabel, 0, 0)
        mainLayout.addWidget(nameLineEditor, 0, 1, 1, 2) #占用的行,列
        mainLayout.addWidget(pwdlabel, 1, 0)
        mainLayout.addWidget(pwdLineEditor, 1, 1, 1, 2)
        mainLayout.addWidget(btnOK, 2, 0)
        mainLayout.addWidget(btnCancel, 2, 1, 1, 2)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QlabelBuddy()
    main.show()
    sys.exit(app.exec_())

 

1.4.设置lineEdit输入框回显模式

4种回显示模式

import sys
from PyQt5.QtWidgets import *


class QLineEditEchoMode(QWidget):
    def __init__(self):
        super(QLineEditEchoMode, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('文本输入框回显模式')
        fromLayout = QFormLayout()

        normalLineEdit = QLineEdit()
        noEchoLineEdit = QLineEdit()
        passwordLineEdit = QLineEdit()
        passwordEchoOnLineEdit = QLineEdit()

        normalLineEdit.setPlaceholderText("normalLineEdit")
        noEchoLineEdit.setPlaceholderText("noEchoLineEdit")
        passwordLineEdit.setPlaceholderText("passwordLineEdit")
        passwordEchoOnLineEdit.setPlaceholderText("passwordEchoOnLineEdit")

        normalLineEdit.setEchoMode(QLineEdit.Normal)
        noEchoLineEdit.setEchoMode(QLineEdit.NoEcho)
        passwordLineEdit.setEchoMode(QLineEdit.Password)
        passwordEchoOnLineEdit.setEchoMode(QLineEdit.PasswordEchoOnEdit)

        fromLayout.addRow("Normal", normalLineEdit)
        fromLayout.addRow("noEchoLineEdit", noEchoLineEdit)
        fromLayout.addRow("passwordLineEdit", passwordLineEdit)
        fromLayout.addRow("passwordEchoOnEdit", passwordEchoOnLineEdit)

        self.setLayout(fromLayout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QLineEditEchoMode()
    main.show()
    sys.exit(app.exec_())

 

1.4.LineEdit检验器

通过设置检验器,检测对应的输入

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIntValidator, QDoubleValidator, QRegExpValidator
from PyQt5.QtCore import QRegExp

class QLineEditValidator(QWidget):
    def __init__(self):
        super(QLineEditValidator, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("校验器")
        formLayout = QFormLayout()
        intLineEdit = QLineEdit()
        doubleLineEdit = QLineEdit()
        validatorLineEdit = QLineEdit()

        formLayout.addRow("整数类型", intLineEdit)
        formLayout.addRow("浮点类型", doubleLineEdit)
        formLayout.addRow("正则表达式", validatorLineEdit)

        intLineEdit.setPlaceholderText("整数")
        doubleLineEdit.setPlaceholderText("小数")
        validatorLineEdit.setPlaceholderText("正则")
        #整型校验器
        intValidator = QIntValidator(self)
        intValidator.setRange(1, 99)
        #浮点校验器
        doubleValidator = QDoubleValidator(self)
        doubleValidator.setRange(-360, 360)
        #标准显示浮点数
        doubleValidator.setNotation(QDoubleValidator.StandardNotation)
        doubleValidator.setDecimals(2)
        #字母和数字
        reg = QRegExp("[a-zA-Z0-9]+$")
        validator = QRegExpValidator(self)
        validator.setRegExp(reg)
        #设置校验器
        intLineEdit.setValidator(intValidator)
        doubleLineEdit.setValidator(doubleValidator)
        validatorLineEdit.setValidator(validator)

        self.setLayout(formLayout)

if __name__ == "__main__":
    app  = QApplication(sys.argv)

    qLineEditValidator = QLineEditValidator()
    qLineEditValidator.show()
    sys.exit(app.exec_())

 

1.5.使用掩码限制QLineEdit的输入

import sys
from PyQt5.QtWidgets import *

class QLineEditMask(QWidget):
    def __init__(self):
        super(QLineEditMask,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("用掩码限制QLineEdit的输入")
        formLayout = QFormLayout()

        ipLineEdit = QLineEdit()
        macLineEdit = QLineEdit()
        dateLineEdit = QLineEdit()
        licenseLineEdit = QLineEdit()

        ipLineEdit.setInputMask("000.000.000.000;_")
        macLineEdit.setInputMask("HH:HH:HH:HH:HH:HH;_")
        dateLineEdit.setInputMask("0000-00-00")
        licenseLineEdit.setInputMask(">AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;#")
        formLayout.addRow("数字掩码", ipLineEdit)
        formLayout.addRow("MAC掩码", macLineEdit)
        formLayout.addRow("date掩码", dateLineEdit )
        formLayout.addRow("许可证掩码", licenseLineEdit)

        self.setLayout(formLayout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QLineEditMask()
    main.show()
    sys.exit(app.exec_())

1.6.文本输入QLineEdit综合例子

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class QLineEditDemo(QWidget):
    def __init__(self):
        super(QLineEditDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QLineEdit综合例子")

        formLayout = QFormLayout()
        self.setLayout(formLayout)

        edit1 = QLineEdit()
        edit1.setValidator(QIntValidator())
        edit1.setMaxLength(4)
        edit1.setFont(QFont('Arial', 20))
        edit1.setAlignment(Qt.AlignRight) #文本在右侧

        edit2 = QLineEdit()
        edit2.setValidator(QDoubleValidator(0.01, 99.99, 2))
        edit2.setMaxLength(5)

        edit3 = QLineEdit()
        edit3.setInputMask("99_9999_999999;#")

        edit4 = QLineEdit()
        edit4.textChanged.connect(self.textChanged)

        edit5 = QLineEdit()
        edit5.setEchoMode(QLineEdit.Password)
        edit5.editingFinished.connect(self.pressEnter)

        edit6 = QLineEdit('hello world')
        edit6.setReadOnly(True)

        formLayout.addRow("整数校验", edit1)
        formLayout.addRow("浮点数校验", edit2)
        formLayout.addRow("Input Mask", edit3)
        formLayout.addRow("文本变化", edit4)
        formLayout.addRow("密码变化", edit5)
        formLayout.addRow("只读文本", edit6)


    def textChanged(self, text):
        print("输入的内容:" + text)

    def pressEnter(self):
        print("输入完成")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QLineEditDemo()
    main.show()
    sys.exit(app.exec_())

 

二.QTextEdit控件

2.1.多行文本输入框的设置,获取

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class QTextEditDemo(QWidget):
        def __init__(self):
            super(QTextEditDemo, self).__init__()
            self.initUI()

        def initUI(self):
            self.setWindowTitle("QEditText控制演示")
            self.resize(300, 400)

            self.textEdit = QTextEdit()
            self.buttonText = QPushButton("显示文本")
            self.buttonHtml = QPushButton("显示HTML")
            self.buttonToText = QPushButton("获取文本")
            self.buttonToHtml = QPushButton("获取HTML")

            layout = QVBoxLayout()
            layout.addWidget(self.textEdit)
            layout.addWidget(self.buttonText)
            layout.addWidget(self.buttonHtml)
            layout.addWidget(self.buttonToText)
            layout.addWidget(self.buttonToHtml)

            self.setLayout(layout)

            self.buttonText.clicked.connect(self.onClick_ButtonText)
            self.buttonHtml.clicked.connect(self.onClick_ButtonHtml)
            self.buttonToText.clicked.connect(self.onClick_ToButtonText)
            self.buttonToHtml.clicked.connect(self.onClick_ToButtonHtml)


        def onClick_ButtonText(self):
            self.textEdit.setPlainText("HELLO WORLD 你好呀")

        def onClick_ButtonHtml(self):
            self.textEdit.setHtml("<FONT COLOR='green'>HELLO WORLD 帅呆了</FONT>")

        def onClick_ToButtonText(self):
            print(self.textEdit.toPlainText())


        def onClick_ToButtonHtml(self):
            print(self.textEdit.toHtml())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QTextEditDemo()
    main.show()
    sys.exit(app.exec_())

 

三.QPushButton按钮

3.1.常见按钮和事件关联2种方式

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class QPushButtonDemo(QDialog):
    def __init__(self):
        super(QPushButtonDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QPushButton Demo")
        layout = QVBoxLayout()

        self.button1 = QPushButton("第一个按钮")
        self.button1.setText("first button")
        self.button1.setCheckable(True)
        self.button1.toggle()
        self.button1.clicked.connect(lambda :self.whichButton(self.button1))
        self.button1.clicked.connect(self.buttonState)

        layout.addWidget(self.button1)
        self.setLayout(layout)
        self.resize(400, 300)

        #文本前显示图片
        self.button2 = QPushButton("图像按钮")
        self.button2.setIcon(QIcon(QPixmap("./image/logo.ico")))
        self.button2.clicked.connect(lambda :self.whichButton(self.button2))
        layout.addWidget(self.button2)
        #不可用按钮
        self.button3 = QPushButton("不可用按钮")
        self.button3.setEnabled(False)
        layout.addWidget(self.button3)
        #默认的按钮
        self.button4 = QPushButton("&Mybutton默认按钮")
        self.button4.setDefault(True)
        self.button4.clicked.connect(lambda :self.whichButton(self.button4))
        layout.addWidget(self.button4)

    def whichButton(self, btn):
        print("被单击的按钮是<" + btn.text() + ">" )

    def buttonState(self):
        if self.button1.isChecked():
            print("按钮已被选中")
        else:
            print("按钮没被选中")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QPushButtonDemo()
    main.show()
    sys.exit(app.exec_())

 

四.QRadionButton单选按钮

4.1.单选按钮状态切换

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QRadioButtonDemo(QWidget):
    def __init__(self):
        super(QRadioButtonDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QRadioButton1")
        layout = QHBoxLayout()

        self.radionButton1 = QRadioButton("单选按钮1")
        self.radionButton1.setChecked(True)
        self.radionButton1.toggled.connect(self.buttonState)
        layout.addWidget(self.radionButton1)

        self.radionButton2 = QRadioButton("单选按钮2")
        self.radionButton2.toggled.connect(self.buttonState)
        layout.addWidget(self.radionButton2)
        self.resize(400, 300)
        self.setLayout(layout)

    def buttonState(self):
        radionButton = self.sender()
        
        if radionButton.isChecked()  == True:
            print("<" + radionButton.text() + ">被选中")
        else:
            print("<" + radionButton.text() + ">未被选中")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main  = QRadioButtonDemo()
    main.show()
    sys.exit(app.exec_())

 

五.QCheckBox复选框按钮

5.1.复选框按钮状态切换和事件触发

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *


class QCheckBoxDemo(QWidget):
    def __init__(self):
        super(QCheckBoxDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QCheckBox演示")
        layout = QHBoxLayout()

        self.checkbox1 = QCheckBox('复选按钮1')
        self.checkbox1.setChecked(True)
        self.checkbox1.stateChanged.connect(lambda :self.checkBoxState(self.checkbox1))
        layout.addWidget(self.checkbox1)

        self.checkbox2 = QCheckBox('复选按钮2')
        self.checkbox2.stateChanged.connect(lambda: self.checkBoxState(self.checkbox2))
        layout.addWidget(self.checkbox2)

        self.checkbox3 = QCheckBox('复选按钮3')
        self.checkbox3.setTristate(True)
        self.checkbox3.setCheckState(Qt.PartiallyChecked)
        self.checkbox3.stateChanged.connect(lambda: self.checkBoxState(self.checkbox3))
        layout.addWidget(self.checkbox3)

        self.setLayout(layout)


    def checkBoxState(self, cb):
        checkstatus1 = self.checkbox1.text() + ', is checked = ' + str(self.checkbox1.isChecked()) + ', checkState = ' + str(self.checkbox1.checkState()) + "\n"
        checkstatus2 = self.checkbox2.text() + ', is checked = ' + str(self.checkbox2.isChecked()) + ', checkState = ' + str(self.checkbox2.checkState()) + "\n"
        checkstatus3 = self.checkbox3.text() + ', is checked = ' + str(self.checkbox3.isChecked()) + ', checkState = ' + str(self.checkbox3.checkState()) + "\n"
        print(checkstatus1 + checkstatus2 + checkstatus3)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QCheckBoxDemo()
    main.show()
    sys.exit(app.exec_())

 

六.下拉列表控件

6.1.下拉列表控制文本设置,方法调用

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QComboBoxDemo(QComboBox):
    def __init__(self):
        super(QComboBoxDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QComboBox Demo")
        layout = QHBoxLayout()
        self.resize(300, 200)

        self.mylable = QLabel("请选择编程语言:")
        self.cb = QComboBox()
        self.cb.addItem("Java")
        self.cb.addItem("PHP")
        self.cb.addItems(["Pyton", "C#", "C++"])
        self.cb.currentIndexChanged.connect(self.selectionChanged)
        layout.addWidget(self.mylable)
        layout.addWidget(self.cb)
        self.setLayout(layout)

    def selectionChanged(self, i):
        self.mylable.setText(self.cb.currentText())
        self.mylable.adjustSize()
        for count in range(self.cb.count()):
            print("item" + str(count) + "=" + self.cb.itemText(count))
        print("courrent index:" , i, 'selection changed', self.cb.currentText())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QComboBoxDemo()
    main.show()
    sys.exit(app.exec_())

 

七.QSpinBox整数调整框

7.1.QSpinBox计数器

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *


class QSpinBoxDemon(QWidget):
    def __init__(self):
        super(QSpinBoxDemon, self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle("QSpinBox Demon")
        self.resize(300, 400)

        layout = QVBoxLayout()
        self.lable = QLabel("当前值")
        self.lable.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.lable)

        self.sb = QSpinBox()
        self.sb.setValue(18)
        self.sb.setSingleStep(3)
        self.sb.setRange(0, 40)

        self.sb.valueChanged.connect(self.valueChange)
        layout.addWidget(self.sb)

        self.setLayout(layout)

    def valueChange(self):
        self.lable.setText("当前值:" + str(self.sb.text()))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QSpinBoxDemon()
    main.show()
    sys.exit(app.exec_())

 

八.滑块控件QSlider

8,1.滑块控件使用和设置

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QSliderDemo(QWidget):
    def __init__(self):
        super(QSliderDemo, self).__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()
        self.setWindowTitle("QSlider Demo")
        self.resize(300, 400)

        self.label = QLabel("Qlable")
        layout.addWidget(self.label)
        #水平间隔
        self.qslider = QSlider(Qt.Horizontal)
        self.qslider.setMinimum(1) #最小值
        self.qslider.setMaximum(100) #最大值
        self.qslider.setTickPosition(QSlider.TicksLeft)
        self.qslider.setValue(50) #默认值
        self.qslider.setSingleStep(5) #按键头键默认步长是5
        self.qslider.setTickInterval(10) #刻度间隔是10,100/10,所以可以显示10个刻度
        self.qslider.valueChanged.connect(self.valueChange)
        layout.addWidget(self.qslider)

        #垂直间隔
        self.qslider1 = QSlider(Qt.Vertical)
        self.qslider1.setMinimum(1)  # 最小值
        self.qslider1.setMaximum(10)  # 最大值
        self.qslider1.setTickPosition(QSlider.TicksBelow)
        # self.qslider1.setValue(5)  # 默认值
        self.qslider1.setSingleStep(1)  # 按键头键默认步长是1
        self.qslider1.setTickInterval(2)  # 刻度间隔是10,10/1,所以可以显示10个刻度
        self.qslider1.valueChanged.connect(self.valueChange)
        layout.addWidget(self.qslider1)

        self.setLayout(layout)

    def valueChange(self):
        size = self.sender().value()
        print("当前值是:%s" % size)
        self.label.setFont(QFont("Aisa", size))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QSliderDemo()
    main.show()
    sys.exit(app.exec_())

 

九.使用Qdialog显示通用对话框

9.1.通用对话框

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QDialogDemo(QMainWindow):
    def __init__(self):
        super(QDialogDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("对话框案例")
        self.resize(300, 400)
        button = QPushButton(self)
        button.move(100, 100)
        button.setText("打开对话框")
        button.clicked.connect(self.showDialog)

    def showDialog(self):
        dialog = QDialog()
        dialog.setWindowTitle("对话框")
        button = QPushButton("确定", dialog)
        dialog.setWindowModality(Qt.ApplicationModal)
        button.clicked.connect(dialog.close)
        button.move(50, 50)
        dialog.exec() #显示对话框

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QDialogDemo()
    main.show()
    sys.exit(app.exec_())

 

十.不同种类的消息对话框QMessagebox

10.1.消息对话框

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QMessageDemo(QWidget):
    def __init__(self):
        super(QMessageDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("不同类型消息对话框")
        self.resize(400, 600)
        layout = QVBoxLayout()

        self.button1 = QPushButton()
        self.button1.setText("显示关于对话框")
        self.button1.clicked.connect(self.showDialog)

        self.button2 = QPushButton()
        self.button2.setText("显示信息对话框")
        self.button2.clicked.connect(self.showDialog)

        self.button3 = QPushButton()
        self.button3.setText("显示警告对话框")
        self.button3.clicked.connect(self.showDialog)

        self.button4 = QPushButton()
        self.button4.setText("显示错误对话框")
        self.button4.clicked.connect(self.showDialog)


        layout.addWidget(self.button1)
        layout.addWidget(self.button2)
        layout.addWidget(self.button3)
        layout.addWidget(self.button4)

        self.setLayout(layout)

    def showDialog(self):
        text = self.sender().text()
        if text == "显示关于对话框":
            QMessageBox.about(self, '关于', '天心数据开发!')
        elif text == "显示信息对话框":
            QMessageBox.information(self, '消息', '这是个提示消息对话框!')
        elif text == "显示警告对话框":
            QMessageBox.warning(self, '警告', '这是个警告对话框!', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        elif text == "显示错误对话框":
            QMessageBox.critical(self, '错误', '这是个错误对话框', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QMessageDemo()
    main.show()
    sys.exit(app.exec_())

 

十一.输入对话框

11.1.不同类型的输入对话框和值的获取 

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QInputDialogDemo(QWidget):
    def __init__(self):
        super(QInputDialogDemo, self).__init__()
        self.initUI()

    def initUI(self):
        layout = QFormLayout()
        self.setWindowTitle("不同类型的输入对话框")
        self.resize(300, 400)

        self.button1 = QPushButton("获取列表中的选项")
        self.lineEdit1 = QLineEdit()
        self.button1.clicked.connect(self.getItem)
        layout.addRow(self.button1, self.lineEdit1)

        self.button2 = QPushButton("获取字符串")
        self.lineEdit2 = QLineEdit()
        self.button2.clicked.connect(self.getText)
        layout.addRow(self.button2, self.lineEdit2)

        self.button3 = QPushButton("获取整数")
        self.lineEdit3 = QLineEdit()
        self.button3.clicked.connect(self.getNum)
        layout.addRow(self.button3, self.lineEdit3)

        self.setLayout(layout)

    def getItem(self):
        items = ("C", "Python", "PHP", "Java")
        item, ok = QInputDialog.getItem(self, '请选择编程语言', '语言列表', items)
        if ok and item:
            self.lineEdit1.setText(item)

    def getText(self):
        text, ok = QInputDialog.getText(self, '文本输入框', '姓名')
        if ok and text:
            self.lineEdit2.setText(text)

    def getNum(self):
        num, ok = QInputDialog.getInt(self, '整数输入框', '数字')
        if ok and num:
            self.lineEdit3.setText(str(num))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QInputDialogDemo()
    main.show()
    sys.exit(app.exec_())

 

十二.字体选择QFontDidlog

12.1选择设置字体

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QFontDialogDemo(QWidget):
    def __init__(self):
        super(QFontDialogDemo, self).__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        self.setWindowTitle("字体对话框")
        self.button1 = QPushButton("选择字体")
        self.button1.clicked.connect(self.getFont)
        self.label1 = QLabel("你好 陌生人")
        layout.addWidget(self.label1)
        layout.addWidget(self.button1)
        self.setLayout(layout)

    def getFont(self):
        font, ok = QFontDialog.getFont(self)
        if ok:
            self.label1.setFont(font)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QFontDialogDemo()
    main.show()
    sys.exit(app.exec_())

 

十三.颜色对话框QColorDialog

13.设置颜色对话框

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QFontDialogDemo(QWidget):
    def __init__(self):
        super(QFontDialogDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QColor Dialog例子")
        self.resize(400, 300)
        layout = QVBoxLayout()

        self.button1 = QPushButton("设置文字颜色")
        self.button1.clicked.connect(self.getColor)
        layout.addWidget(self.button1)

        self.button2 = QPushButton("设置背景颜色")
        self.button2.clicked.connect(self.getBgColor)
        layout.addWidget(self.button2)

        self.label = QLabel("天心数据")
        layout.addWidget(self.label)

        self.setLayout(layout)

    def getColor(self):
        color = QColorDialog.getColor() #颜色对话框
        p = QPalette() #色板
        p.setColor(QPalette.WindowText, color) #设置改变文字色板颜色 
        self.label.setPalette(p) #用色板来调节lable颜色

    def getBgColor(self):
        color = QColorDialog.getColor()
        p = QPalette()
        p.setColor(QPalette.Window, color)
        self.label.setAutoFillBackground(True)
        self.label.setPalette(p)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QFontDialogDemo()
    main.show()
    sys.exit(app.exec_())

 

十四.文件对话框QDialog

14.1文件对话框QDialog

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QDialogDemo(QWidget):
    def __init__(self):
        super(QDialogDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("文件对话框案例")
        self.resize(300, 400)
        layout = QVBoxLayout()

        self.button1 = QPushButton("加载图片")
        self.button1.clicked.connect(self.loadImg)
        layout.addWidget(self.button1)

        self.button2 = QPushButton("加载文本")
        self.button2.clicked.connect(self.loadText)
        layout.addWidget(self.button2)

        self.imgLabel = QLabel()
        layout.addWidget(self.imgLabel)

        self.connents = QTextEdit()
        layout.addWidget(self.connents)

        self.setLayout(layout)


    def loadImg(self):
        fname, _ = QFileDialog.getOpenFileName(self, '打开文件', '.', '图文件(*.png, *.jpg)')
        self.imgLabel.setPixmap(QPixmap(fname))

    def loadText(self):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setFilter(QDir.Files)
        if dialog.exec():
            filenames = dialog.selectedFiles()
            f = open(filenames[0], encoding="utf-8", mode='r')
            with f:
                data = f.read()
                self.connents.setText(data)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QDialogDemo()
    main.show()
    sys.exit(app.exec_())

 

十五.用象素点绘制正弦曲线

16.1.用画笔工具绘制象素点

import sys, math
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QColor, QFont
from PyQt5.QtCore import Qt


class DrawPoints(QWidget):
    def __init__(self):
        super(DrawPoints, self).__init__()
        self.setWindowTitle("在窗口上绘制正弦曲线")

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setPen(Qt.red)
        size = self.size()
        for i in range(1000):
            x = 100*(-1 + 2.0*i/1000) + size.width()/2
            y = -50 * math.sin((x -size.width()/2)*math.pi/50) + size.height()/2
            painter.drawPoint(x, y)
        painter.end()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = DrawPoints()
    main.show()
    sys.exit(app.exec_())

 

十六.绘制不同类型的直线

16.1.用画笔绘制不同类型的直接

import sys, math
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QColor, QFont, QPen
from PyQt5.QtCore import Qt


class DrawMutilineDemo(QWidget):
    def __init__(self):
        super(DrawMutilineDemo, self).__init__()
        self.setWindowTitle("在窗口上绘制任意曲线")
        self.resize(300, 400)

    def paintEvent(self,  event):
        painter = QPainter()
        painter.begin(self)

        pen = QPen(Qt.red, 3, Qt.SolidLine)
        painter.setPen(pen)
        painter.drawLine(20, 40, 250, 40)

        pen.setStyle(Qt.DashLine)
        painter.setPen(pen) #修改了画笔,需要重新设置下才会生效
        painter.drawLine(20, 60, 250, 60)

        pen.setStyle(Qt.DashDotDotLine)
        painter.setPen(pen)
        painter.drawLine(20, 80, 250, 80)

        pen.setStyle(Qt.DotLine)
        painter.setPen(pen)
        painter.drawLine(20, 100, 250, 100)

        pen.setStyle(Qt.DashDotLine)
        painter.setPen(pen)
        painter.drawLine(20, 120, 250, 120)

        pen.setStyle(Qt.CustomDashLine)
        pen.setDashPattern([1, 5, 10, 15])
        painter.setPen(pen)
        painter.drawLine(20, 140, 250, 160)
        painter.end()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = DrawMutilineDemo()
    main.show()
    sys.exit(app.exec_())

 

十七.绘制任意图象

17.1.绘制弧,扇形,圆,弦,任意多边形,图片

import sys, math
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QColor, QFont, QPen, QPolygon, QImage
from PyQt5.QtCore import Qt, QRect, QPoint


class DrawAllDemo(QWidget):
    def __init__(self):
        super(DrawAllDemo, self).__init__()
        self.setWindowTitle("在窗口上绘制任意图象")
        self.resize(400, 600)

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        qp.setPen(Qt.red)

        #绘制弧
        rect = QRect(40, 40, 100, 100) #设置弧区域
        qp.drawArc(rect, 0, 90*16)
        #通过弧度绘制圆
        qp.drawArc(160, 40, 100, 100, 0, 360*16)
        #带弦的弧
        qp.drawChord(40, 120, 100, 100, 0, 90*16)
        #绘扇形
        qp.drawPie(10, 240, 100, 100, 0, 60*16)
        #绘制椭圆
        qp.drawEllipse(40, 360, 150, 100)
        #绘制多边形
        point1 = QPoint(100, 500)
        point2 = QPoint(300, 500)
        point3 = QPoint(150, 400)
        point4 = QPoint(450, 550)
        polygon = QPolygon([point1, point2, point3, point4])
        qp.drawPolygon(polygon)

        #绘制图象
        image = QImage(".\image\logo.png")
        rect = QRect(40, 500, image.width(), image.height())
        qp.drawImage(rect, image)

        qp.end()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = DrawAllDemo()
    main.show()
    sys.exit(app.exec_())

 

十八.笔刷填充

18.1.笔刷填充图形区域

import sys, math
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QColor, QFont, QPen, QPolygon, QImage, QBrush
from PyQt5.QtCore import Qt, QRect, QPoint


class DrawAllDemo(QWidget):
    def __init__(self):
        super(DrawAllDemo, self).__init__()
        self.setWindowTitle("用笔刷填充矩形")
        self.resize(600, 600)

    def paintEvent(self, event):
        panit = QPainter()
        panit.begin(self)

        brush = QBrush(Qt.SolidPattern)
        panit.setBrush(brush)
        panit.drawRect(10, 40,90, 60)

        brush = QBrush(Qt.Dense1Pattern)
        panit.setBrush(brush)
        panit.drawRect(130, 40, 90, 60)

        brush = QBrush(Qt.Dense2Pattern)
        panit.setBrush(brush)
        panit.drawRect(240, 40, 90, 60)

        brush = QBrush(Qt.Dense3Pattern)
        panit.setBrush(brush)
        panit.drawRect(10, 110, 90, 60)

        panit.end()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = DrawAllDemo()
    main.show()
    sys.exit(app.exec_())

 

十九.拖拽控件

19.1.用法,需要设置允许拖动和接收2个事件.

import sys, math
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QFormLayout, QLabel, QLineEdit
from PyQt5.QtGui import QPainter, QColor, QFont, QPen, QPolygon, QImage, QBrush
from PyQt5.QtCore import Qt, QRect, QPoint


class MyComboBox(QComboBox):
    def __init__(self):
        super(MyComboBox, self).__init__()
        self.setAcceptDrops(True) #允许接收

    def dragEnterEvent(self, e):#拖进去时触发
        print(e)
        if e.mimeData().hasText():
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e): #松开鼠标触发
        self.addItem(e.mimeData().text())


class DragDropDemo(QWidget):
    def __init__(self):
        super(DragDropDemo, self).__init__()
        self.resize(600, 600)


        formlayout = QFormLayout()
        formlayout.addRow(QLabel("把左边的文字,拖到右边的控件选项中去"))

        lineEdit = QLineEdit()
        lineEdit.setDragEnabled(True) #让控件可以拖动

        mycombobox = MyComboBox()
        formlayout.addRow(lineEdit, mycombobox)

        self.setLayout(formlayout)
        self.setWindowTitle("拖拽控制案例")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = DragDropDemo()
    main.show()
    sys.exit(app.exec_())

 

二十.剪贴板数据库的复制和粘贴

20.1.应用中剪贴板的文本,html,图片库复制和粘,贴

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ClipBoradDemo(QDialog):
    def __init__(self):
        super(ClipBoradDemo, self).__init__()
        textCopyButton = QPushButton("复制文本")
        textPasteButton = QPushButton("粘贴文本")

        htmlCopyButton = QPushButton("复制Html")
        htmlPasteButton = QPushButton("粘贴Html")

        imageCopyButton = QPushButton("复制图象")
        imagePasteButton = QPushButton("粘贴图象")

        self.textLabel = QLabel("默认文本")
        self.imgLabel = QLabel()

        layout = QGridLayout()
        layout.addWidget(textCopyButton, 0, 0)
        layout.addWidget(htmlCopyButton, 0, 1)
        layout.addWidget(imageCopyButton, 0, 2)

        layout.addWidget(textPasteButton, 1, 0)
        layout.addWidget(htmlPasteButton, 1, 1)
        layout.addWidget(imagePasteButton, 1, 2)

        layout.addWidget(self.textLabel, 2, 0)
        layout.addWidget(self.imgLabel,2, 0)

        textCopyButton.clicked.connect(self.copyText)
        textPasteButton.clicked.connect(self.pasteText)
        htmlCopyButton.clicked.connect(self.copyHtml)
        htmlPasteButton.clicked.connect(self.pasteHtml)
        imageCopyButton.clicked.connect(self.copyImg)
        imagePasteButton.clicked.connect(self.pasteImg)

        self.setLayout(layout)

    def copyText(self):
        clipboard = QApplication.clipboard()
        clipboard.setText("hello Worald")

    def pasteText(self):
        clipBoard = QApplication.clipboard()
        print(clipBoard.text())
        self.textLabel.setText(clipBoard.text())

    def copyHtml(self):
        mimeData = QMimeData()
        mimeData.setHtml("<b>bold <font color=red>red</font></b>")
        clipboard = QApplication.clipboard()
        clipboard.setMimeData(mimeData)

    def pasteHtml(self):
        clipboard = QApplication.clipboard()
        mimeData = clipboard.mimeData()

        if mimeData.hasHtml():
            self.textLabel.setText(mimeData.html())


    def copyImg(self):
        clipboard = QApplication.clipboard()
        clipboard.setPixmap(QPixmap('./image/logo.png'))
        print("copy img")


    def pasteImg(self):
        clipboard = QApplication.clipboard()
        self.imgLabel.setPixmap(clipboard.pixmap())
        print("paste img")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = ClipBoradDemo()
    main.show()
    sys.exit(app.exec_())


 

二十一.日历控件

21.1.日历控件日期获取和显示

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class MyCalenderDemo(QWidget):
    def __init__(self):
        super(MyCalenderDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(400, 800)
        self.calender = QCalendarWidget(self)
        self.calender.setMinimumDate(QDate(1988, 1,1))
        self.calender.setMaximumDate(QDate(2088, 1, 1))
        self.calender.setGridVisible(True)
        self.calender.clicked.connect(self.showDate)

        self.calender.move(20,20)
        self.label = QLabel(self)
        self.label.move(20, 400)
        date = self.calender.selectedDate()
        self.label.setText(date.toString("yyyy-MM-dd dddd"))
        self.setWindowTitle("日历演示")

    def showDate(self, date):
        # self.label.setText(date.toString("yyyy-MM-dd dddd"))
        self.label.setText(self.calender.selectedDate().toString("yyyy-MM-dd dddd"))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MyCalenderDemo()
    main.show()
    sys.exit(app.exec_())

 

二十二.设置时间编辑控件

22.1.显示格式QDateTimeEdit

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class MyDateTime(QWidget):
    def __init__(self):
        super(MyDateTime, self).__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()
        self.setWindowTitle("不同风格的日期显示修改")
        self.resize(400, 600)
        dateTimeEditor1 = QDateTimeEdit() #设置控件显示的时间
        dateTimeEditor2 = QDateTimeEdit(QDateTime.currentDateTime())
        dateEditor = QDateTimeEdit(QDate.currentDate())
        timeEditor = QDateTimeEdit(QTime.currentTime())

        dateTimeEditor2.setMinimumDate(QDate.currentDate().addDays(-365))
        dateTimeEditor2.setMaximumDate(QDate.currentDate().addDays(365))
        dateTimeEditor2.setCalendarPopup(True)

        dateTimeEditor1.dateChanged.connect(self.ondateChange)
        dateTimeEditor1.timeChanged.connect(self.ontimeChange)
        dateTimeEditor1.dateTimeChanged.connect(self.ondateTimeChange)

        dateTimeEditor1.setDisplayFormat("yyyy-MM-dd HH:mm:ss") #设置显示的格式
        dateTimeEditor2.setDisplayFormat("yyyy/MM/dd HH-mm-ss")
        dateEditor.setDisplayFormat("yy.MM.dd")
        timeEditor.setDisplayFormat("HH:mm:ss")

        layout.addWidget(dateTimeEditor1)
        layout.addWidget(dateTimeEditor2)
        layout.addWidget(dateEditor)
        layout.addWidget(timeEditor)

        self.setLayout(layout)

    def ontimeChange(self, time):
        print(time)
    def ondateChange(self, date):
        print(date)
    def ondateTimeChange(self, datetime):
        print(datetime)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MyDateTime()
    main.show()
    sys.exit(app.exec_())

 

二十三.菜单

23.1.菜单添加设置和触发

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class Menu(QMainWindow):
    def __init__(self):
        super(Menu, self).__init__()
        self.resize(300, 400)
        self.setWindowTitle("菜单测试")

        bar = self.menuBar() #获取菜单
        file = bar.addMenu("文件")#新建菜单

        new = file.addAction("新建")
        new.setShortcut("Ctrl + N")

        save = QAction("保存", self)
        save.setShortcut("Ctrl + S")
        file.addAction(save)
        save.triggered.connect(self.process)
        new.triggered.connect(self.process)

        edit = bar.addMenu("编辑")
        copy = edit.addAction("复制")
        paste = edit.addAction("粘贴")
        copy.triggered.connect(self.process)
        paste.triggered.connect(self.process)
    def process(self):
        print(self.sender().text())



if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = Menu()
    main.show()
    sys.exit(app.exec_())

 

二十四.工具栏Toolbar

24,.1.工具栏的创建,触发,显示样式

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class MyTool(QMainWindow):
    def __init__(self):
        super(MyTool, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(300, 400)
        self.setWindowTitle("工具栏测试")
        tb1 = self.addToolBar("File")
        newpng = QAction(QIcon('./image/New.png'), "新建", self)
        openpng = QAction( QIcon('./image/Open.png'), "open", self )
        savepng = QAction(QIcon('./image/Save.png'), "save", self)
        tb1.addAction(newpng)
        tb1.addAction(openpng)
        tb1.addAction(savepng)
        # tb1.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)#设置提示文本样式

        tb2 = self.addToolBar("second")
        newpng2 = QAction(QIcon("./image/New.png"), "NEW", self)
        tb2.addAction(newpng2)
        tb2.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        tb1.actionTriggered.connect(self.toolbarprocess)
        tb2.actionTriggered.connect(self.toolbarprocess)

    def toolbarprocess(self, a):
        print("当前按下的按钮是:", a.text())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MyTool()
    main.show()
    sys.exit(app.exec_())

 

二十四.状态栏

24.1.设置状态栏

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class MyStatusBar(QMainWindow):
    def __init__(self):
        super(MyStatusBar, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(300, 400)
        self.setWindowTitle("状态栏测试")
        bar = self.menuBar() #建立菜单
        file = bar.addMenu("File") #建立菜单选项
        file.addAction("show") #添加子选项
        self.setCentralWidget(QTextEdit())
        self.sb = QStatusBar()
        self.setStatusBar(self.sb) #设置状态栏
        file.triggered.connect(self.processTrigger)


    def processTrigger(self, p):
        if p.text() == "show":
            self.sb.showMessage(p.text() + "菜单被点击了", 5000)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MyStatusBar()
    main.show()
    sys.exit(app.exec_())

 

二十五.显示二维表数据

25.1.QtabelView表格控件显示

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class MyStatusBar(QWidget):
    def __init__(self):
        super(MyStatusBar, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(600, 400)
        self.setWindowTitle("QtabelView表格视图控件显示")

        self.model = QStandardItemModel(4, 3)
        self.model.setHorizontalHeaderLabels(["id", "姓名", "age"])

        self.tabelView = QTableView()
        self.tabelView.setModel(self.model) #关联model

        item00 = QStandardItem("1")
        item01 = QStandardItem("天心")
        item02 = QStandardItem("28")

        item10 = QStandardItem("2")
        item11 = QStandardItem("泥泥")
        item12 = QStandardItem("33")

        self.model.setItem(0, 0, item00)
        self.model.setItem(0, 1, item01)
        self.model.setItem(0, 2, item02)
        self.model.setItem(1, 0, item10)
        self.model.setItem(1, 1, item11)
        self.model.setItem(1, 2, item12)


        layout = QVBoxLayout()
        layout.addWidget(self.tabelView)
        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MyStatusBar()
    main.show()
    sys.exit(app.exec_())

 

二十六.显示列数据

26.1.QlistView显示列数据

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class ListViewDemo(QWidget):
    def __init__(self):
        super(ListViewDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(600, 400)
        self.setWindowTitle("QListView列表视图控件显示")
        layout = QVBoxLayout()

        listview = QListView()
        listmode = QStringListModel() #建立个空的model

        self.list = ["列表项1", "列表项2", "列表项3",] #建立数据
        listmode.setStringList(self.list)  #把数据关联model

        listview.setModel(listmode) #设置listview的数据
        listview.clicked.connect(self.clicked)
        layout.addWidget(listview)

        self.setLayout(layout)

    def clicked(self, item):
        QMessageBox.information(self, 'QlistView', '你当前点击了' + self.list[item.row()])

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = ListViewDemo()
    main.show()
    sys.exit(app.exec_())

 

二十六.扩展的列表控件QlistWidget

26.1.显示,触发

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class QlistWidgetDemo(QMainWindow):
    def __init__(self):
        super(QlistWidgetDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QlistWidget扩展的列表控件")
        self.listWidget = QListWidget()
        self.listWidget.addItem("PYTHON")
        self.listWidget.addItem("PHP")
        self.listWidget.addItem("JAVA")
        self.listWidget.addItem("NET")

        self.listWidget.itemClicked.connect(self.clicked)
        self.setCentralWidget(self.listWidget)

    def clicked(self, index):
        print(self.listWidget.item(self.listWidget.row(index)).text()) #先获取 行,通过行找item.在用text打印文本
        QMessageBox.information(self, "QListWidget", "你选择:" + self.listWidget.item(self.listWidget.row(index)).text())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QlistWidgetDemo()
    main.show()
    sys.exit(app.exec_())

 

二十七.扩展的表格控件QTableWidget

27.1.设置表格的数据,样式

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class QTabelWidgetDemo(QWidget):
    def __init__(self):
        super(QTabelWidgetDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTabelWidget扩展的表格控件")
        layout = QHBoxLayout()
        tabelWidget = QTableWidget()
        tabelWidget.setColumnCount(3) #设置表格多少列
        tabelWidget.setRowCount(4) #设置表格多少行

        tabelWidget.setHorizontalHeaderLabels(["姓名", "年龄", "籍贯"])
        nameitem = QTableWidgetItem("小明")
        ageitem = QTableWidgetItem("22")
        additem = QTableWidgetItem("汉")

        tabelWidget.setItem(0, 0, nameitem)
        tabelWidget.setItem(0, 1, ageitem)
        tabelWidget.setItem(0, 2, additem)

        nameitem = QTableWidgetItem("小鸽")
        ageitem = QTableWidgetItem("29")
        additem = QTableWidgetItem("汉")

        tabelWidget.setItem(1, 0, nameitem)
        tabelWidget.setItem(1, 1, ageitem)
        tabelWidget.setItem(1, 2, additem)

        tabelWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) #表格设置为不可编辑
        tabelWidget.setSelectionBehavior(QAbstractItemView.SelectRows) #选择整行
        tabelWidget.resizeColumnsToContents() #调整单元格列自适应内容
        # tabelWidget.resizeRowsToContents() #调整单元行自适应内容

        tabelWidget.horizontalHeader().setVisible(False) #设置不显示水平表头
        # tabelWidget.verticalHeader().setVisible(False) #设置不显示垂直表头
        tabelWidget.setVerticalHeaderLabels(['a', 'b'])
        tabelWidget.setShowGrid(False)
        layout.addWidget(tabelWidget)


        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QTabelWidgetDemo()
    main.show()
    sys.exit(app.exec_())

 

二十八.表格中放置控件

28.1.表格的单元格放文本,控制方法

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class PlaceControllInCellDemo(QWidget):
    def __init__(self):
        super(PlaceControllInCellDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("表格单元格中放置控件")
        self.resize(430, 300)
        layout = QHBoxLayout()

        tabelWidget = QTableWidget()
        tabelWidget.setRowCount(4)
        tabelWidget.setColumnCount(3)
        tabelWidget.setHorizontalHeaderLabels(["name", "sex", "age"])

        textItem = QTableWidgetItem("泥泥")
        tabelWidget.setItem(0, 0, textItem) #将文本放在单元格中

        combox = QComboBox()
        combox.addItem('男')
        combox.addItem('女')
        combox.setStyleSheet("QComboBox{margin:3px;}") #QSS设置样式
        tabelWidget.setCellWidget(0, 1,combox) #将控件放在单元格中

        button = QPushButton("修改")
        tabelWidget.setStyleSheet("QPushButton{margin:3px}")
        tabelWidget.setCellWidget(0, 2, button)


        layout.addWidget(tabelWidget)
        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = PlaceControllInCellDemo()
    main.show()
    sys.exit(app.exec_())

 

二十九.表格中单元格的搜索和定位

29.1.单元格的搜索后定位,设置前,背景色颜色

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class DataLocation(QWidget):
    def __init__(self):
        super(DataLocation, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("表格单元格中放置控件")
        self.resize(430, 300)
        layout = QVBoxLayout()
        self.tabel = QTableWidget()
        self.tabel.setRowCount(40)
        self.tabel.setColumnCount(4)

        for i in range(40):
            for j in range(4):
                itemContent = '%d, %d' %(i, j)
                self.tabel.setItem(i, j, QTableWidgetItem(itemContent))

        self.text = QLineEdit()
        self.searchBtn = QPushButton("搜索")
        self.searchBtn.clicked.connect(self.search)

        layout.addWidget(self.text)
        layout.addWidget(self.searchBtn)
        layout.addWidget(self.tabel)
        self.setLayout(layout)

    def search(self):
        print(self.text.text())
        items = self.tabel.findItems(self.text.text(), Qt.MatchExactly)
        if len(items) > 0:
            item = items[0] #满足条件的第一个值
            item.setBackground(QBrush(QColor(0, 255, 0))) #设置背景色颜色
            item.setForeground(QBrush(QColor(255, 0, 0)))
            row = item.row() #获取当前所在的行号
            self.tabel.verticalScrollBar().setSliderPosition(row) #定位滚动条到指定的行


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = DataLocation()
    main.show()
    sys.exit(app.exec_())

 

三十.设置单元格字体颜色和大小

30.1.单元格颜色,大小,字体设置

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class CellFontColor(QWidget):
    def __init__(self):
        super(CellFontColor, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("表格单元格的颜色和字体大小")
        self.resize(400, 300)
        layout = QHBoxLayout()
        tabelWidget = QTableWidget()
        tabelWidget.setColumnCount(3) #设置表格多少列
        tabelWidget.setRowCount(4) #设置表格多少行

        newItem = QTableWidgetItem("雷神")
        newItem.setFont(QFont("Times", 14, QFont.Black)) #设置字体,大小.黑体
        newItem.setForeground(QBrush(QColor(255,0, 0))) #设置颜色为红色
        tabelWidget.setItem(0, 0, newItem)

        newItem = QTableWidgetItem("女")
        newItem.setForeground(QBrush(QColor(255, 255, 0))) 
        newItem.setBackground(QBrush(QColor(0, 255, 0))) #设置背景色
        tabelWidget.setItem(0, 1, newItem)

        newItem = QTableWidgetItem("80")
        newItem.setFont(QFont("Times", 16, QFont.Normal))
        newItem.setForeground(QBrush(QColor(0, 255, 0)))

        tabelWidget.setItem(0, 2, newItem)

        layout.addWidget(tabelWidget)
        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = CellFontColor()
    main.show()
    sys.exit(app.exec_())

 

三十一.表格的列排序

31.1.升,降序排序列

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class CellFontColor(QWidget):
    def __init__(self):
        super(CellFontColor, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("表格列排序")
        self.resize(400, 300)
        layout = QVBoxLayout()
        self.tabelWidget = QTableWidget()
        self.tabelWidget.setColumnCount(3) #设置表格多少列
        self.tabelWidget.setRowCount(4) #设置表格多少行
        self.tabelWidget.setHorizontalHeaderLabels(["Name", "Sex", "Weight"])

        newitem = QTableWidgetItem("张三")
        self.tabelWidget.setItem(0, 0, newitem)
        newitem = QTableWidgetItem("男")
        self.tabelWidget.setItem(0, 1, newitem)
        newitem = QTableWidgetItem("120")
        self.tabelWidget.setItem(0, 2, newitem)

        newitem = QTableWidgetItem("李四")
        self.tabelWidget.setItem(1, 0, newitem)
        newitem = QTableWidgetItem("女")
        self.tabelWidget.setItem(1, 1, newitem)
        newitem = QTableWidgetItem("150")
        self.tabelWidget.setItem(1, 2, newitem)

        newitem = QTableWidgetItem("王五")
        self.tabelWidget.setItem(2, 0, newitem)
        newitem = QTableWidgetItem("女")
        self.tabelWidget.setItem(2, 1, newitem)
        newitem = QTableWidgetItem("110")
        self.tabelWidget.setItem(2, 2, newitem)

        self.btn = QPushButton('排序')
        # self.tabelWidget.setCellWidget(3, 2, self.btn)

        self.orderType = Qt.DescendingOrder #设置默认升序

        self.btn.clicked.connect(self.sort)
        layout.addWidget(self.tabelWidget)
        layout.addWidget(self.btn)
        self.setLayout(layout)

    def sort(self):
        if self.orderType == Qt.DescendingOrder: #实现按钮切换
            self.orderType = Qt.AscendingOrder
        else:
            self.orderType = Qt.DescendingOrder

        self.tabelWidget.sortItems(2, self.orderType) #实现排序

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = CellFontColor()
    main.show()
    sys.exit(app.exec_())

 

三十二.表格中文本对齐方式

32.1.表格中文本对齐方式

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class TextAlignDemo(QWidget):
    def __init__(self):
        super(TextAlignDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("表格列排序")
        self.resize(400, 300)
        layout = QVBoxLayout()
        self.tabelWidget = QTableWidget()
        self.tabelWidget.setColumnCount(3) #设置表格多少列
        self.tabelWidget.setRowCount(4) #设置表格多少行
        self.tabelWidget.setHorizontalHeaderLabels(["Name", "Sex", "Weight"])

        newitem = QTableWidgetItem("张三")
        newitem.setTextAlignment(Qt.AlignRight | Qt.AlignBottom)
        self.tabelWidget.setItem(0, 0, newitem)

        newitem = QTableWidgetItem("男")
        newitem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.tabelWidget.setItem(0, 1, newitem)

        newitem = QTableWidgetItem("120")
        newitem.setTextAlignment(Qt.AlignRight)
        self.tabelWidget.setItem(0, 2, newitem)

        newitem = QTableWidgetItem("李四")
        newitem.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.tabelWidget.setItem(1, 0, newitem)
        newitem = QTableWidgetItem("女")
        self.tabelWidget.setItem(1, 1, newitem)
        newitem = QTableWidgetItem("150")
        self.tabelWidget.setItem(1, 2, newitem)

        newitem = QTableWidgetItem("王五")
        self.tabelWidget.setItem(2, 0, newitem)
        newitem = QTableWidgetItem("女")
        self.tabelWidget.setItem(2, 1, newitem)
        newitem = QTableWidgetItem("110")
        self.tabelWidget.setItem(2, 2, newitem)


        layout.addWidget(self.tabelWidget)

        self.setLayout(layout)



if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = TextAlignDemo()
    main.show()
    sys.exit(app.exec_())

 

三十三.单元格合并

33.1.表格中单元格合并

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class SpanDemo(QWidget):
    def __init__(self):
        super(SpanDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("单元格合并")
        self.resize(400, 300)
        layout = QVBoxLayout()
        self.tabelWidget = QTableWidget()
        self.tabelWidget.setColumnCount(3) #设置表格多少列
        self.tabelWidget.setRowCount(4) #设置表格多少行
        self.tabelWidget.setHorizontalHeaderLabels(["Name", "Sex", "Weight"])

        newitem  = QTableWidgetItem("雷神")
        self.tabelWidget.setItem(0, 0, newitem)
        self.tabelWidget.setSpan(0, 0, 3, 1)  #0, 0单元格,占用3行,1列

        newitem  = QTableWidgetItem("男")
        self.tabelWidget.setItem(0, 1, newitem)
        self.tabelWidget.setSpan(0, 1, 2, 1)

        newitem  = QTableWidgetItem("120")
        self.tabelWidget.setItem(0, 2, newitem)

        layout.addWidget(self.tabelWidget)

        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = SpanDemo()
    main.show()
    sys.exit(app.exec_())

 

三十四.表格设置行,列大小

34.1.设置表格的行高,列宽

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class CellSizeDemo(QWidget):
    def __init__(self):
        super(CellSizeDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("表格列排序")
        self.resize(400, 300)
        layout = QVBoxLayout()
        self.tabelWidget = QTableWidget()
        self.tabelWidget.setColumnCount(3) #设置表格多少列
        self.tabelWidget.setRowCount(4) #设置表格多少行
        self.tabelWidget.setHorizontalHeaderLabels(["Name", "Sex", "Weight"])

        newitem = QTableWidgetItem("张三")
        self.tabelWidget.setRowHeight(0, 100) #设置行高
        newitem.setTextAlignment(Qt.AlignRight | Qt.AlignBottom)
        self.tabelWidget.setItem(0, 0, newitem)

        newitem = QTableWidgetItem("男")
        newitem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.tabelWidget.setColumnWidth(1, 200) #设置列宽
        self.tabelWidget.setItem(0, 1, newitem)

        newitem = QTableWidgetItem("120")
        newitem.setTextAlignment(Qt.AlignRight)
        self.tabelWidget.setItem(0, 2, newitem)

        newitem = QTableWidgetItem("李四")
        newitem.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.tabelWidget.setItem(1, 0, newitem)
        newitem = QTableWidgetItem("女")
        self.tabelWidget.setItem(1, 1, newitem)
        newitem = QTableWidgetItem("150")
        self.tabelWidget.setItem(1, 2, newitem)

        newitem = QTableWidgetItem("王五")
        self.tabelWidget.setItem(2, 0, newitem)
        newitem = QTableWidgetItem("女")
        self.tabelWidget.setItem(2, 1, newitem)
        newitem = QTableWidgetItem("110")
        self.tabelWidget.setItem(2, 2, newitem)


        layout.addWidget(self.tabelWidget)

        self.setLayout(layout)



if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = CellSizeDemo()
    main.show()
    sys.exit(app.exec_())

 

三十四.单元格中放图片

34.1.表格中的单元格如何放图片和文字

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class CellImageDemo(QWidget):
    def __init__(self):
        super(CellImageDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("单元格中显示图片")
        self.resize(400, 300)
        layout = QVBoxLayout()
        self.tabelWidget = QTableWidget()
        self.tabelWidget.setColumnCount(3) #设置表格多少列
        self.tabelWidget.setRowCount(4) #设置表格多少行
        self.tabelWidget.setHorizontalHeaderLabels(["Name", "Sex", "头象"])

        newitem = QTableWidgetItem("小明")
        self.tabelWidget.setItem(0, 0, newitem)

        newitem = QTableWidgetItem("男")
        self.tabelWidget.setItem(0, 1, newitem)

        newitem = QTableWidgetItem(QIcon("./image/logo.png"), "天心数据") #放图片
        self.tabelWidget.setItem(0, 2, newitem)

        layout.addWidget(self.tabelWidget)
        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = CellImageDemo()
    main.show()
    sys.exit(app.exec_())

 

三十五.单元格设置显示图片大小

35.1.设置单元格和图片大小

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class CellImageSizeDemo(QWidget):
    def __init__(self):
        super(CellImageSizeDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("表格列排序")
        self.resize(1000, 900)

        layout = QVBoxLayout()
        self.tabelWidget = QTableWidget()
        self.tabelWidget.setIconSize(QSize(200, 60)) #设置单元格所有图片显示大小
        self.tabelWidget.setColumnCount(3) #设置表格多少列
        self.tabelWidget.setRowCount(5) #设置表格多少行

        self.tabelWidget.setHorizontalHeaderLabels(["图片1", "图片2", "图片3"])
        #设置单元格和图片一样大
        for i in range(5):
            self.tabelWidget.setRowHeight(i, 60)

        for j in range(3):
            self.tabelWidget.setColumnWidth(j, 200)
        #单元格中放图片
        for i in range(5):
            for j in range(3):
                newitem = QTableWidgetItem()
                newitem.setIcon(QIcon("./image/logo.png"))
                self.tabelWidget.setItem(i, j, newitem)

        layout.addWidget(self.tabelWidget)
        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = CellImageSizeDemo()
    main.show()
    sys.exit(app.exec_())

 

三十六.设置表格中的上下文

36.1.设置表格右键的菜单项

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class TabelWidgetContextDemo(QWidget):
    def __init__(self):
        super(TabelWidgetContextDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("表格中显示上下文菜单")
        self.resize(400, 300)
        layout = QVBoxLayout()
        self.tabelWidget = QTableWidget()
        self.tabelWidget.setColumnCount(3) #设置表格多少列
        self.tabelWidget.setRowCount(4) #设置表格多少行
        self.tabelWidget.setHorizontalHeaderLabels(["Name", "Sex", "Weight"])

        newitem = QTableWidgetItem("张三")
        self.tabelWidget.setItem(0, 0, newitem)

        newitem = QTableWidgetItem("男")
        self.tabelWidget.setItem(0, 1, newitem)

        newitem = QTableWidgetItem("120")
        self.tabelWidget.setItem(0, 2, newitem)

        newitem = QTableWidgetItem("李四")
        newitem.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.tabelWidget.setItem(1, 0, newitem)

        newitem = QTableWidgetItem("女")
        self.tabelWidget.setItem(1, 1, newitem)

        newitem = QTableWidgetItem("150")
        self.tabelWidget.setItem(1, 2, newitem)

        newitem = QTableWidgetItem("王五")
        self.tabelWidget.setItem(2, 0, newitem)

        newitem = QTableWidgetItem("女")
        self.tabelWidget.setItem(2, 1, newitem)

        newitem = QTableWidgetItem("110")
        self.tabelWidget.setItem(2, 2, newitem)

        self.tabelWidget.setContextMenuPolicy(Qt.CustomContextMenu) #允许弹出上下文菜单
        self.tabelWidget.customContextMenuRequested.connect(self.generateMenu)
        layout.addWidget(self.tabelWidget)

        self.setLayout(layout)

    def generateMenu(self, pos):
        print(pos)
        for i in self.tabelWidget.selectionModel().selection().indexes(): #循环选中行的索引
            print(i)  #输出<PyQt5.QtCore.QModelIndex object at 0x0000000002D84B38>
            rowNum = i.row()
            print(rowNum) #输出选中的单元格所在行号

        if rowNum < 2: #如果选中是前2行,
            menu = QMenu()
            item1 = menu.addAction("删除")
            item2 = menu.addAction("剪切")
            item3 = menu.addAction("粘贴")
            #坐标映射到全局
            screenPos = self.tabelWidget.mapToGlobal(pos)
            # 被阻塞,除非你单击菜单项
            action = menu.exec(screenPos)
            if action == item1:
                print("你选中第1个菜单项:",
                      self.tabelWidget.item(rowNum, 0).text(),
                      self.tabelWidget.item(rowNum, 1).text(),
                      self.tabelWidget.item(rowNum, 2).text(),
                      )
            elif action == item2:
                print("你选中第2个菜单项:",
                      self.tabelWidget.item(rowNum, 0).text(),
                      self.tabelWidget.item(rowNum, 1).text(),
                      self.tabelWidget.item(rowNum, 2).text(),
                      )
            elif action == item3:
                print("你选中第3个菜单项:",
                      self.tabelWidget.item(rowNum, 0).text(),
                      self.tabelWidget.item(rowNum, 1).text(),
                      self.tabelWidget.item(rowNum, 2).text(),
                      )
            else:
                return


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = TabelWidgetContextDemo()
    main.show()
    sys.exit(app.exec_())

 

三十七.树控件

37.1.树控件的设置,展开,添加图标基本用法

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class BaseTreeWidgetDemo(QMainWindow):
    def __init__(self):
        super(BaseTreeWidgetDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("基本树控件")
        self.tree = QTreeWidget()
        #指定树的列数
        self.tree.setColumnCount(2)

        #指定列标签
        self.tree.setHeaderLabels(['key', 'value'])
        root = QTreeWidgetItem(self.tree)
        root.setText(0, "根节点")
        root.setIcon(0, QIcon('.\image\open.png'))
        self.tree.setColumnWidth(0, 150)

        #添加子节点1
        child1 = QTreeWidgetItem(root)
        child1.setText(0, "子节点1")
        child1.setText(1, "子节点1的数据")
        child1.setIcon(0, QIcon("./image/logo.png"))
        child1.setCheckState(0, Qt.Checked) #添加复选框

        child2 = QTreeWidgetItem(root)
        child2.setText(0, "子节点2")
        child2.setText(1, "子节点2数据")
        child2.setIcon(0, QIcon("./image/logo.png"))

        child3 = QTreeWidgetItem(child2)
        child3.setText(0, "子节点2-1")
        child3.setText(1,"新的值")

        self.tree.expandAll()
        self.setCentralWidget(self.tree)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = BaseTreeWidgetDemo()
    main.show()
    sys.exit(app.exec_())

 

三十八.树节点事件

38.1.树节点响应事件

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class TreeEventDemo(QMainWindow):
    def __init__(self):
        super(TreeEventDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("树控件响应事件")
        self.tree = QTreeWidget()
        self.tree.setColumnCount(2)
        self.tree.setHeaderLabels(["key", "value"])

        root = QTreeWidgetItem(self.tree)
        root.setText(0, 'root')
        root.setText(1, '根节点数据')

        child1 = QTreeWidgetItem(root)
        child1.setText(0, "child1")
        child1.setText(1, 'child1数据')

        child2 = QTreeWidgetItem(root)
        child2.setText(0, "child2")
        child2.setText(1, "child2数据")

        child3 = QTreeWidgetItem(child2)
        child3.setText(0, "child3")
        child3.setText(1, "child3数据")

        self.tree.expandAll()
        self.tree.clicked.connect(self.onclickTree)
        self.setCentralWidget(self.tree)

    def onclickTree(self, index):
        item = self.tree.currentItem()
        print("节点索引:%d" %(index.row())) #此处的节点索引,是相对于当前的父节点.是第几个.
        print('key=%s, value=%s' %(item.text(0), item.text(1)))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = TreeEventDemo()
    main.show()
    sys.exit(app.exec_())

 

 

三十九.动态修改子节点

39.1.树节点的增加,删除,修改

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ModifyTreeDemo(QWidget):
    def __init__(self):
        super(ModifyTreeDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("动态修改树控件")
        layout = QVBoxLayout()

        addbtn = QPushButton("增加节点")
        updatebtn = QPushButton("更新节点")
        delbtn = QPushButton("删除节点")

        addbtn.clicked.connect(self.addNode)
        updatebtn.clicked.connect(self.updateNode)
        delbtn.clicked.connect(self.deleteNode)

        layout.addWidget(addbtn)
        layout.addWidget(updatebtn)
        layout.addWidget(delbtn)

        self.tree = QTreeWidget()
        self.tree.setColumnCount(2)
        self.tree.setHeaderLabels(["key", "value"])

        root = QTreeWidgetItem(self.tree)
        root.setText(0, 'root')
        root.setText(1, '根节点数据')

        child1 = QTreeWidgetItem(root)
        child1.setText(0, "child1")
        child1.setText(1, 'child1数据')

        child2 = QTreeWidgetItem(root)
        child2.setText(0, "child2")
        child2.setText(1, "child2数据")

        child3 = QTreeWidgetItem(child2)
        child3.setText(0, "child3")
        child3.setText(1, "child3数据")

        self.tree.expandAll()
        self.tree.clicked.connect(self.onclickTree)
        layout.addWidget(self.tree)
        self.setLayout(layout)

    def onclickTree(self, index):
        item = self.tree.currentItem()
        print("节点索引:%d" %(index.row())) #此处的节点索引,是相对于当前的父节点.是第几个.
        print('key=%s, value=%s' %(item.text(0), item.text(1)))

    def addNode(self):
        print("增加节点")
        parent = self.tree.currentItem() or self.tree.invisibleRootItem()
        newitem = QTreeWidgetItem(parent )
        newitem.setText(0, "新增节点")
        newitem.setText(1, "新增节点数据")

    def updateNode(self):
        print("修改节点")
        curitem = self.tree.currentItem()
        curitem.setText(0, "修改后的节点")
        curitem.setText(1, "修改后的值")

    def deleteNode(self):
        print("删除节点")
        curitem = self.tree.currentItem()
        root = self.tree.invisibleRootItem() #最顶层节点,的不可见根

        for item in self.tree.selectedItems():
            print(item.parent())
            (item.parent() or root).removeChild(item) #通过父节点移除指定的子节点


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = ModifyTreeDemo()
    main.show()
    sys.exit(app.exec_())

 

四十.QTreeView控件使用

40.1.显示系统目录树

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


if __name__ == "__main__":
    app = QApplication(sys.argv)
    model = QDirModel() #显示目录结构模型
    tree = QTreeView()
    tree.setModel(model)

    tree.setWindowTitle('QTreeView')
    tree.resize(600, 400)
    tree.show()
    sys.exit(app.exec_())

 

四十一.标签页

41.1.标签页的添加和控件增加

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class TabWidgetDemo(QTabWidget): #继承的类
    def __init__(self):
        super(TabWidgetDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("标签页控件")
        self.resize(300, 200)
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()

        self.addTab(self.tab1, "标签页1")
        self.addTab(self.tab2, "标签页2")
        self.addTab(self.tab3, "标签页3")

        self.tab1UI()
        self.tab2UI()
        self.tab3UI()

    def tab1UI(self):
        layout = QFormLayout()
        layout.addRow("姓名:", QLineEdit())
        layout.addRow("地址:", QLineEdit())
        self.setTabText(0, "联系方式")
        self.tab1.setLayout(layout) #设置标签页布局


    def tab2UI(self):
        layout = QFormLayout()
        sex = QHBoxLayout()
        sex.addWidget(QRadioButton("男"))
        sex.addWidget(QRadioButton("女"))
        layout.addRow("性别:", sex) #增加水平布局
        layout.addRow("生日:", QCalendarWidget())
        self.setTabText(1, "个人详细信息")
        self.tab2.setLayout(layout)

    def tab3UI(self):
        layout = QHBoxLayout()
        layout.addWidget(QLabel("学历"))
        layout.addWidget(QCheckBox("高中"))
        layout.addWidget(QCheckBox("本科"))
        self.setTabText(2, "教育")
        self.tab3.setLayout(layout)



if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = TabWidgetDemo()
    main.show()
    sys.exit(app.exec_())

 

四十二.使用堆栈窗口显示不同的页面

42.1.QStackedWidget控件的使用

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class QStackWidgetDemo(QWidget): #继承的类
    def __init__(self):
        super(QStackWidgetDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("堆栈页控件")

        self.list = QListWidget()
        self.list.insertItem(0, "联系方式")
        self.list.insertItem(1, "个人信息")
        self.list.insertItem(0, "教育程度")
        self.list.currentRowChanged.connect(self.display) #点击列表时.切换不同的页面

        self.stack1 = QWidget() #建立3个窗口
        self.stack2 = QWidget()
        self.stack3 = QWidget()

        self.tab1UI()
        self.tab2UI()
        self.tab3UI()

        self.stack = QStackedWidget() #创建堆栈窗口对象
        self.stack.addWidget(self.stack1)
        self.stack.addWidget(self.stack2)
        self.stack.addWidget(self.stack3)


        hbox = QHBoxLayout()
        hbox.addWidget(self.list) #左侧显示列表,右侧显示页面
        hbox.addWidget(self.stack)

        self.setLayout(hbox)


    def display(self, index):
        self.stack.setCurrentIndex(index)  #根据索引,切换栈里面的页面


    def tab1UI(self):
        layout = QFormLayout()
        layout.addRow("姓名:", QLineEdit())
        layout.addRow("地址:", QLineEdit())

        self.stack1.setLayout(layout) #设置标签页布局


    def tab2UI(self):
        layout = QFormLayout()
        sex = QHBoxLayout()
        sex.addWidget(QRadioButton("男"))
        sex.addWidget(QRadioButton("女"))
        layout.addRow("性别:", sex) #增加水平布局
        layout.addRow("生日:", QCalendarWidget())

        self.stack2.setLayout(layout)

    def tab3UI(self):
        layout = QHBoxLayout()
        layout.addWidget(QLabel("学历"))
        layout.addWidget(QCheckBox("高中"))
        layout.addWidget(QCheckBox("本科"))

        self.stack3.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QStackWidgetDemo()
    main.show()
    sys.exit(app.exec_())

 

四十三.悬浮控件

43.1.悬浮控制使用

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class QDockWidgetDemo(QMainWindow): #继承的类
    def __init__(self):
        super(QDockWidgetDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("停靠控件")
        # layout = QHBoxLayout()
        self.list = QListWidget()
        self.list.addItem("item1")
        self.list.addItem("item2")
        self.list.addItem("item3")

        self.dock = QDockWidget("名字" ,self) #创建悬浮窗口
        self.dock.setWidget(self.list)

        # self.dock.setFloating(True) #设置窗口默认状态悬浮

        self.setCentralWidget(QLineEdit())
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock) #当前窗口添加,并指定悬浮区域


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QDockWidgetDemo()
    main.show()
    sys.exit(app.exec_())

 

四十四.多文档窗口

44.1.多文档窗口区域设置和显示

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class MutilWindowDemo(QMainWindow): #继承的类
    count = 0
    def __init__(self):
        super(MutilWindowDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("容纳多文档窗口")
        self.mdi = QMdiArea() #新建多文档区域

        bar = self.menuBar() #新建菜单
        file = bar.addMenu("File") #添加选项
        file.addAction("New")
        file.addAction("Cascade")
        file.addAction("Tiled")

        file.triggered.connect(self.windowAction)

        self.setCentralWidget(self.mdi)


    def windowAction(self, q):
        if q.text() == "New" :
            MutilWindowDemo.count += + 1
            sub = QMdiSubWindow() #新建子窗口
            sub.setWidget(QTextEdit()) #子窗口添加控件
            sub.setWindowTitle("子窗口" + str(MutilWindowDemo.count)) #子窗口设置标题
            self.mdi.addSubWindow(sub) #把子窗口添加到文档区域
            sub.show() #显示子窗口

        elif q.text() == "Cascade":
            self.mdi.cascadeSubWindows() #层叠显示
        elif q.text() == "Tiled":
            self.mdi.tileSubWindows() #平铺显示子窗口


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MutilWindowDemo()
    main.show()
    sys.exit(app.exec_())


 

四十五.滚动条

45.1.滚动条改变其它控制状态和位置

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ScrollBarDemo(QWidget): #继承的类
    count = 0
    def __init__(self):
        super(ScrollBarDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("滚动条")
        hbox = QHBoxLayout()
        self.label = QLabel("我会变化的")

        self.scroolBar1 = QScrollBar()
        self.scroolBar1.setMaximum(255)
        self.scroolBar1.sliderMoved.connect(self.onsliderMove)

        self.scroolBar2 = QScrollBar()
        self.scroolBar2.setMaximum(255)
        self.scroolBar2.sliderMoved.connect(self.onsliderMove)

        self.scroolBar3 = QScrollBar()
        self.scroolBar3.setMaximum(255)
        self.scroolBar3.sliderMoved.connect(self.onsliderMove)

        self.scroolBar4 = QScrollBar()
        self.scroolBar4.setMaximum(255)
        self.scroolBar4.sliderMoved.connect(self.onsliderMove2)

        self.y = self.label.y() #保留当前label坐标

        hbox.addWidget(self.label)
        hbox.addWidget(self.scroolBar1)
        hbox.addWidget(self.scroolBar2)
        hbox.addWidget(self.scroolBar3)
        hbox.addWidget(self.scroolBar4)

        self.setLayout(hbox)
        self.setGeometry(600, 300, 300, 200)

    def onsliderMove(self):
        print(self.scroolBar1.value(), self.scroolBar2.value(), self.scroolBar3.value())
        p = QPalette() #建立调色板
        c = QColor(self.scroolBar1.value(), self.scroolBar2.value(), self.scroolBar3.value(), 255) #设置颜色
        p.setColor(QPalette.Foreground, c) #调色板设置前景色
        self.label.setPalette(p)

    def onsliderMove2(self):
        self.label.move(self.label.x(), self.y + self.scroolBar4.value())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = ScrollBarDemo()
    main.show()
    sys.exit(app.exec_())

 

四十六.定时器Ontimer

46.1.使用定时器实现时间刷新

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ShowTimerDemo(QWidget): #继承的类
    count = 0
    def __init__(self):
        super(ShowTimerDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("定时器显示时间")
        self.resize(400, 300)
        layout = QGridLayout()
        self.label = QLabel(QDateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))
        self.startBtn = QPushButton("开始显示")
        self.endBtn = QPushButton("结束显示")
        self.endBtn.setEnabled(False)

        self.timer = QTimer() #建立定时器
        self.timer.timeout.connect(self.showTimer) #定时器执行的方法

        self.startBtn.clicked.connect(self.startTimer)
        self.endBtn.clicked.connect(self.stopTimer)

        layout.addWidget(self.label, 0, 0, 1, 2)
        layout.addWidget(self.startBtn, 1, 0)
        layout.addWidget(self.endBtn, 1, 1)

        self.setLayout(layout)
    def showTimer(self):
        timer = QDateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
        self.label.setText(timer)

    def startTimer(self):
        self.timer.start(1000) #开启定时器,并设置间隔
        self.startBtn.setEnabled(False) #开始按钮禁用
        self.endBtn.setEnabled(True) #结束按钮可用

    def stopTimer(self):
        self.timer.stop()
        self.startBtn.setEnabled(True)
        self.endBtn.setEnabled(False)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = ShowTimerDemo()
    main.show()
    sys.exit(app.exec_())

 

四十七.定时器静态方法延时执行

47.1.延时执行一段代码

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


if __name__ == "__main__":
    app = QApplication(sys.argv)
    label = QLabel("<font size=20 color=red><b>5秒后关闭此窗口</b></font>")
    label.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint) #设置窗口显示样式
    label.show()
    QTimer.singleShot(5000, app.quit) #5秒后执行退出程序.此方法适合延时执行一段代码
    sys.exit(app.exec_())

 

四十八.使用浏览器控件

48.1.浏览器控件打开网页

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *


class WebEngineView(QMainWindow):
    def __init__(self):
        super(WebEngineView, self).__init__()
        self.setWindowTitle("打开外部网页例子")
        self.setGeometry(30, 50, 1355, 730)
        self.browser = QWebEngineView()
        self.browser.load(QUrl("https://www.ttgame.net"))
        self.setCentralWidget(self.browser)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = WebEngineView()
    main.show()
    sys.exit(app.exec_())

 

四十九.装载本地电脑html页面

49.1.装载本地html文件

import sys, os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *


class WebEngineView(QMainWindow):
    def __init__(self):
        super(WebEngineView, self).__init__()
        self.setWindowTitle("装载本地页面")
        self.setGeometry(30, 50, 1355, 730)
        self.browser = QWebEngineView()
        url = os.getcwd() + "./test.html"
        self.browser.load(QUrl.fromLocalFile(url))
        self.setCentralWidget(self.browser)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = WebEngineView()
    main.show()
    sys.exit(app.exec_())

 

五十.加载html代码

50.1.直接加载html代码

import sys, os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *


class WebEngineView(QMainWindow):
    def __init__(self):
        super(WebEngineView, self).__init__()
        self.setWindowTitle("直接加载html代码")
        self.setGeometry(30, 50, 1355, 730)
        self.browser = QWebEngineView()
        self.browser.setHtml('''
        <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>测试页面</title>
            </head>
            <body>
            <h2>pyqt5</h2>
            <h3>pyqt5</h3>
            <h4>pyqt5</h4>
            <h5>pyqt5</h5>
            
            </body>
            </html>
        ''')

        self.setCentralWidget(self.browser)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = WebEngineView()
    main.show()
    sys.exit(app.exec_())

 

五十一.按按右下角排列

51.1.布局按钮在右下角

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *


class RightBottomBtn(QWidget):
    def __init__(self):
        super(RightBottomBtn, self).__init__()
        self.setWindowTitle("按钮右下角")

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        okBtn = QPushButton("确定")
        cancelBtn = QPushButton("取消")
        hbox.addWidget(okBtn)
        hbox.addWidget(cancelBtn)

        vbox = QVBoxLayout()
        vbox.addStretch(0) #优先排列
        btn1 = QPushButton("按钮1")
        btn2 = QPushButton("按钮2")
        btn3 = QPushButton("按钮3")
        vbox.addWidget(btn1)
        vbox.addWidget(btn2)
        vbox.addWidget(btn3)

        vbox.addStretch(1) #占余下位置
        vbox.addLayout(hbox)

        self.setLayout(vbox)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = RightBottomBtn()
    main.show()
    sys.exit(app.exec_())

 

五十二.控件延展量

52.1.控件所占相对百分比,设置为延展量0的优先排列,余下的位置.给其它非0的控件

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *


class StrechDemo(QWidget):
    def __init__(self):
        super(StrechDemo, self).__init__()
        self.setWindowTitle("控件升缩量")
        self.resize(800, 100)
        hbox = QHBoxLayout()
        
        btn1  = QPushButton("按钮1")
        btn2  = QPushButton("按钮2")
        btn3  = QPushButton("按钮3")
        hbox.addStretch(1) #添加前设置
        hbox.addWidget(btn1)
        hbox.addStretch(2)
        hbox.addWidget(btn2)
        hbox.addStretch(3)
        hbox.addWidget(btn3)

        # hbox.addStretch(1)
        # btnOK= QPushButton("确定")
        # btnCancel = QPushButton("取消")


        # hbox.addWidget(btnOK)
        # hbox.addWidget(btnCancel)
        self.setLayout(hbox)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = StrechDemo()
    main.show()
    sys.exit(app.exec_())

 

五十三.表单布局

53.1.使用网格布局设置表单

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *


class GirdFormDemo(QWidget):
    def __init__(self):
        super(GirdFormDemo, self).__init__()
        self.setWindowTitle("栅格布局:表单设计")
        titleLable = QLabel("标题")
        authorLable = QLabel("作者")
        contentLabel = QLabel("内容")

        titleEdit = QLineEdit()
        authorEdit = QLineEdit()
        contentEdit = QTextEdit()

        layout = QGridLayout()
        layout.addWidget(titleLable, 1, 0)
        layout.addWidget(titleEdit, 1, 1)

        layout.addWidget(authorLable,2, 0)
        layout.addWidget(authorEdit,2, 1)

        layout.addWidget(contentLabel, 3, 0)
        layout.addWidget(contentEdit, 3, 1, 5, 1) #设置所在的行,列,占用的行,列数

        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = GirdFormDemo()
    main.show()
    sys.exit(app.exec_())

 

五十四.控件可移动边界

54.1.控件移动边界

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *


class GirdFormDemo(QWidget):
    def __init__(self):
        super(GirdFormDemo, self).__init__()
        self.setWindowTitle("拖动边界")
        hbox = QHBoxLayout()
        self.setGeometry(300, 300, 300, 200)

        topLeft = QFrame()
        topLeft.setFrameShape(QFrame.StyledPanel)
        topRight = QTextEdit()

        bottom  = QFrame()
        bottom.setFrameShape(QFrame.StyledPanel)

        splitter1 = QSplitter(Qt.Horizontal) #水平可以移动边界
        splitter1.addWidget(topLeft)
        splitter1.addWidget(topRight)
        splitter1.setSizes([100, 200]) #设置所有宽度

        splitter2 = QSplitter(Qt.Vertical) #垂直移动边界
        splitter2.addWidget(splitter1)
        splitter2.addWidget(bottom)
        
        hbox.addWidget(splitter2)
        self.setLayout(hbox)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = GirdFormDemo()
    main.show()
    sys.exit(app.exec_())

 

五十五.自定义信号与槽

55.1.自定义信号与槽的使用触发

from PyQt5.QtCore import *

class MyTypeSignal(QObject):
    sendmsg = pyqtSignal(object) #定义一个信号

    def run(self): #想触发信号调用此方法
        self.sendmsg.emit("Hello Tony") #触发信号,并传参


class MySolt(QObject):
    def get(self, msg): #处理接收到信号
        print("信息:" + msg)


if __name__ == "__main__":
    sender = MyTypeSignal()
    solt = MySolt()

    sender.sendmsg.connect(solt.get) #信号绑定方法
    sender.run() #运行

    sender.sendmsg.disconnect(solt.get) #解除信号与槽的绑定
    sender.run()

 

五十六.类添加多个信号

56.1.同一个信号,传递多个参数的重载.

from PyQt5.QtCore import *


class MutilSignal(QObject):
    signal1 = pyqtSignal()
    signal2 = pyqtSignal(int)
    signal3 = pyqtSignal(int, str)
    signal4 = pyqtSignal(list)
    signal5 = pyqtSignal(dict)
    signal6 = pyqtSignal([int, str], [str]) #申明一个重载版本信号,[]代表传入参数可以是int,str的.也可以只有一个的str参数类型

    def __init__(self):
        super(MutilSignal, self).__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[int, str].connect(self.signalCall6) #关联时指定
        self.signal6[str].connect(self.signalCall6Overload)
        # self.signal5.connect(self.signalCall5)

    def signalCall1(self):
        print("signal1 emit")

    def signalCall2(self, val):
        print("signal2 emit, value:", val)

    def signalCall3(self, val, text):
        print("signal3 emit, value:", val, text)

    def signalCall4(self, val):
        print("signal4 emit, value:", val)

    def signalCall5(self, val):
        print("signal5 emit, value:", val)

    def signalCall6(self, val, text):
        print("signal6 emit, value:", val, text)

    def signalCall6Overload(self, text):
        print("signal6 overload emit, value:", text)


if __name__ == "__main__":
    myMutilSignal = MutilSignal()
    myMutilSignal.signal1.emit()
    myMutilSignal.signal2.emit(2)
    myMutilSignal.signal3.emit(100, "signal3:hello world")
    myMutilSignal.signal4.emit(["a", "b", "c"])
    myMutilSignal.signal5.emit({"name":"tony", "age":18})
    myMutilSignal.signal6[int, str].emit(1314, "signalcall6") #调用时也需要要显示指定参数类型
    myMutilSignal.signal6[str].emit("overload")

 

五十七.窗口添加信号

57.1.使用窗口信号关闭窗口

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class WinSignal(QMainWindow):
    btn_click_signal = pyqtSignal() #定义个没有参数的信号

    def __init__(self):
        super(WinSignal, self).__init__()
        self.setWindowTitle("为窗口添加信号")
        self.resize(400, 300)
        btn = QPushButton("关闭窗口", self)

        btn.clicked.connect(self.btn_clicked) #按钮添加槽
        self.btn_click_signal.connect(self.btnClose) #信号绑定的槽

    def btn_clicked(self):
        self.btn_click_signal.emit() #触发信号

    def btnClose(self):
        self.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    winSignal = WinSignal()
    winSignal.show()
    sys.exit(app.exec_())

 

五十八.多线程更新UI数据

58.1.使用线程,不同类之间传递数据

import sys, time
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class BackendThread(QThread): #定义个后台运行的线程,每1秒更新时间,并传出个时间字符串
    update_time = pyqtSignal(str)

    def run(self):
        while True:
            data = QDateTime.currentDateTime()
            current_date_time = data.toString("yyyy-MM-dd hh:mm:ss")
            self.update_time.emit(current_date_time)
            time.sleep(1)


class ThreadUpdateUI(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setWindowTitle("多线程更新UI数据")
        self.resize(400, 300)
        self.input = QLineEdit(self)
        self.input.resize(400, 300)

        self.initUI()

    def initUI(self):
        self.backendThread = BackendThread()
        self.backendThread.update_time.connect(self.handDisplay) #对线程的信号绑定当前类的方法.实现传递参数
        self.backendThread.start()

    def handDisplay(self, data): #接收信号传来的参数
        self.input.setText(data)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    winSignal = ThreadUpdateUI()
    winSignal.show()
    sys.exit(app.exec_())

 

五十九.信号与槽的自动连接

59.1.信号与槽,通过对象名自动连接

import sys, time
from PyQt5 import QtCore
from PyQt5.QtWidgets import *

class AutoSignalSolt(QWidget):
    def __init__(self):
        super(AutoSignalSolt, self).__init__()

        self.okbtn = QPushButton("OK")
        self.okbtn.setObjectName("okButton") #与槽的方法名有对应关每次

        self.cancel_btn = QPushButton("Cancel")
        self.cancel_btn.setObjectName("cancelBtn")

        hbox = QHBoxLayout()
        hbox.addWidget(self.okbtn)
        hbox.addWidget(self.cancel_btn)
        self.setLayout(hbox)

        QtCore.QMetaObject.connectSlotsByName(self) #需要放在setlayout后面才触发
        # self.okbtn.clicked.connect(self.on_okButton_clicked)


    @QtCore.pyqtSlot()
    def on_okButton_clicked(self): #槽的命名规则on_对象名_信号
        print("ok btn solt")

    @QtCore.pyqtSlot()
    def on_cancelBtn_clicked(self):
        print("cancel btn solt")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = AutoSignalSolt()
    main.show()
    sys.exit(app.exec_())

 

六十.使用lamba表达式传递参数

60.1.使用lamba表达式实现槽的多个参数传递

import sys, time
from PyQt5 import QtCore
from PyQt5.QtWidgets import *


class LambaSoltArg(QMainWindow):
    def __init__(self):
        super(LambaSoltArg, self).__init__()
        self.setWindowTitle("使用Lamba 表达式传递参数")

        self.btn1 = QPushButton("按钮1")
        self.btn2 = QPushButton("按钮2")

        self.btn1.clicked.connect(lambda :self.on_btn_clicked(10, 20))
        self.btn2.clicked.connect(lambda :self.on_btn_clicked(100, 200))

        layout = QHBoxLayout()
        layout.addWidget(self.btn1)
        layout.addWidget(self.btn2)
        mainFrame = QWidget()
        mainFrame.setLayout(layout)
        self.setCentralWidget(mainFrame)


    def on_btn_clicked(self, m, n):
        print("结果为:", str(m + n))
        QMessageBox.information(self, "结果为:", str(m + n))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = LambaSoltArg()
    main.show()
    sys.exit(app.exec_())

 

六十一.使用partial传递参数

61.1.传递参数另外种方法

import sys, time
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from functools import partial

class LambaSoltArg(QMainWindow):
    def __init__(self):
        super(LambaSoltArg, self).__init__()
        self.setWindowTitle("使用Lamba 表达式传递参数")

        self.btn1 = QPushButton("按钮1")
        self.btn2 = QPushButton("按钮2")
        x = 100
        y = 200
        self.btn1.clicked.connect(partial(self.on_btn_clicked, 10, 20))
        self.btn2.clicked.connect(partial(self.on_btn_clicked, x, y))

        # self.btn1.clicked.connect(lambda :self.on_btn_clicked(10, 20))
        # self.btn2.clicked.connect(lambda :self.on_btn_clicked(100, 200))

        layout = QHBoxLayout()
        layout.addWidget(self.btn1)
        layout.addWidget(self.btn2)
        mainFrame = QWidget()
        mainFrame.setLayout(layout)
        self.setCentralWidget(mainFrame)


    def on_btn_clicked(self, m, n):
        print("结果为:", str(m + n))
        QMessageBox.information(self, "结果为:", str(m + n))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = LambaSoltArg()
    main.show()
    sys.exit(app.exec_())

 

六十二.多窗口不使用信号实现数据交互

62.1.调用其它窗口的控件来实现数据交互,耦合度高.不推荐 

import sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class DateDialog(QDialog):
    def __init__(self, parent=None):
        super(DateDialog, self).__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)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

    def dateTime(self):
        return self.datetime.dateTime() #返回当前时间

    @staticmethod
    def getDateTime():
        dialog = DateDialog(parent = None)
        result = dialog.exec() #显示对话框
        date = dialog.dateTime() #获取日期时间
        return (date.date(), date.time(), result == QDialog.Accepted)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = DateDialog()
    print(main.dateTime())
    main.show()

    sys.exit(app.exec_())

 

六十三.使用信号与槽不同窗口来传递数据

63.1.不同窗口推荐使用自定义信号与槽来传递数据,尽量避免访问其它窗口控件,降低程序之间耦合度

A,B窗口,B窗口是子窗口.

把自定义信号定计在子窗口B中,可以通过自定义信号往A窗口传数据

自定义信号槽,关联在A窗口中

A窗口代码

import sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from newDialog import DateDialog

class MutilWindows2(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("设置多窗口交互使用信号与槽")
        self.resize(400, 300)

        self.lineEdit_inner = QLineEdit(self) #用来显示时间
        self.lineEdit_inner.setText("接收子窗口内置信号时间")
        self.lineEdit_Emit = QLineEdit(self)
        self.lineEdit_Emit.setText("接收子窗口自定义信号时间")

        self.openBtn = QPushButton("获取时间")
        self.openBtn.clicked.connect(self.openDialog)

        vbox = QVBoxLayout()
        vbox.addWidget(self.lineEdit_inner)
        vbox.addWidget(self.lineEdit_Emit)
        vbox.addWidget(self.openBtn)

        self.setLayout(vbox)

    def openDialog(self):
        dailog = DateDialog(self)
        dailog.datetime_inner.dateTimeChanged.connect(self.deal_inner_solt) #需要访问另外窗口控件,设置其对应的槽函数

        dailog.Signal_OneParameter.connect(self.deal_emit_solt) #给自定义信号关联槽
        dailog.show()

    def deal_inner_solt(self, date): #接收日历返回的时间
        self.lineEdit_inner.setText(date.toString()) #显示在当前窗口

    def deal_emit_solt(self, date):
        self.lineEdit_Emit.setText(date)  # 显示在当前窗口

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MutilWindows2()
    main.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(DateDialog, self).__init__(parent)
        self.setWindowTitle("子窗口用来发射信号")
        self.resize(100, 150)
        layout = QVBoxLayout(self)

        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())  # 设置时间控件的时间

        self.datetime_emit.dateTimeChanged.connect(self.emit_signal) #关联槽方法

        layout.addWidget(self.datetime_inner)
        layout.addWidget(self.datetime_emit)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

    def emit_signal(self): #获取当前控件时间,并触发信号对应的槽函数
        date_str = self.datetime_emit.dateTime().toString()
        self.Signal_OneParameter.emit(date_str)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = DateDialog()
    main.show()

    sys.exit(app.exec_())

 

 

 

 

 

 

 

 

 

0
0

评论提问