PyQt5 基本窗口控件(按钮类/对话框类)

2022-05-10 10:06:47 浏览数 (1)

文章目录
  • 1. 按钮类
    • 1.1 QPushButton
    • 1.2 QRadioButton
    • 1.3 QCheckBox
    • 1.4 QComboBox 下拉列表
    • 1.5 QSpinBox 计数器
    • 1.6 QSlider 滑动条
  • 2. 对话框类
    • 2.1 QDialog
    • 2.2 QMessageBox
    • 2.3 QInputDialog
    • 2.4 QFontDialog
    • 2.5 QFileDialog

learn from 《PyQt5 快速开发与实战》 https://doc.qt.io/qtforpython/index.html https://www.riverbankcomputing.com/static/Docs/PyQt5

1. 按钮类

所有的按钮都是继承自 QAbstractButton

1.1 QPushButton

  • 长方形,文本标题 or 图标

设置快捷键:QPushButton('&Download')& 后面的字符就是快捷键,ALT D 执行

代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 21:01
# @Author : Michael
# @File : qpush_button1.py
# @desc :

import sys

from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QPushButton, QApplication


class Form(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("QPushButton例子")
        layout = QVBoxLayout()

        self.button1 = QPushButton("Button1")
        self.button1.setCheckable(True)  # 设置按钮已经被选中,表示按钮保持已点击和释放状态
        self.button1.toggle()  # 切换按钮的状态
        self.button1.clicked.connect(lambda: self.whichButton(self.button1))
        # lambda 函数作用,可以传递更多的参数进去 self.button1
        self.button1.clicked.connect(self.btnstate)
        layout.addWidget(self.button1)

        self.button2 = QPushButton("image")
        self.button2.setIcon(QIcon(QPixmap("logo.png"))) # 设置图标
        self.button2.clicked.connect(lambda: self.whichButton(self.button2))
        layout.addWidget(self.button2)

        self.button3 = QPushButton("disabled button")
        self.button3.setEnabled(False) # 禁用
        layout.addWidget(self.button3)

        self.button4 = QPushButton("&Cancel")
        self.button4.setDefault(True)
        self.button4.clicked.connect(lambda: self.whichButton(self.button4))
        layout.addWidget(self.button4)

        self.setLayout(layout)

    def btnstate(self):
        if self.button1.isChecked():
            print("button1 is pressed")
        else:
            print("button1 is released")

    def whichButton(self, btn):
        print("clicked button is "   btn.text())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = Form()
    ui.show()
    sys.exit(app.exec_())

1.2 QRadioButton

  • 单选按钮组里,一次只能选中一个单选按钮
  • 要选中多个,需要使用 QGroupBox,QButtonGroup多个按钮组合
  • 按钮切换状态时,会发送 toggled 信号
代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 21:34
# @Author : Michael
# @File : radio_button1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QRadioButton, QApplication


class radio_button(QWidget):
    def __init__(self):
        super(radio_button, self).__init__()
        layout = QHBoxLayout()

        self.button1 = QRadioButton("Button1")
        self.button1.setChecked(True) # 默认选中
        self.button1.toggled.connect(lambda: self.btnstate(self.button1))
        layout.addWidget(self.button1)

        self.button2 = QRadioButton("Button2")
        self.button2.toggled.connect(lambda: self.btnstate(self.button2))
        layout.addWidget(self.button2)

        self.setLayout(layout)
        self.setWindowTitle("RadioButton例子")

    def btnstate(self, btn):
        if btn.text() == "Button1":
            if btn.isChecked():
                print("Button1 is selected")
            else:
                print("Button1 is deselected")
        elif btn.text() == "Button2":
            if btn.isChecked():
                print("Button2 is selected")
            else:
                print("Button2 is deselected")


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    example = radio_button()
    example.show()
    sys.exit(app.exec_())

1.3 QCheckBox

一组带文本标签的复选框(可设置文本 or 图标),可选多个选项

注意:有选中、没选中、半选中(setTristate)3 种状态

代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 21:58
# @Author : Michael
# @File : check_box1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QGroupBox, QHBoxLayout, QCheckBox, QVBoxLayout, QApplication
from PyQt5.QtCore import Qt


class checkBox(QWidget):
    def __init__(self):
        super().__init__()

        groupbox = QGroupBox("CheckBoxes")
        groupbox.setFlat(True)

        layout = QHBoxLayout()

        self.checkbox1 = QCheckBox("&CheckBox1")
        self.checkbox1.setChecked(True)
        self.checkbox1.stateChanged.connect(lambda: self.checkbox_state(self.checkbox1))
        layout.addWidget(self.checkbox1)

        self.checkbox2 = QCheckBox("CheckBox2")
        self.checkbox2.toggled.connect(lambda: self.checkbox_state(self.checkbox2))
        layout.addWidget(self.checkbox2)

        self.checkbox3 = QCheckBox("CheckBox3")
        self.checkbox3.setTristate(True)
        self.checkbox3.setCheckState(Qt.PartiallyChecked)
        self.checkbox3.stateChanged.connect(lambda: self.checkbox_state(self.checkbox3))
        layout.addWidget(self.checkbox3)

        groupbox.setLayout(layout)
        main_layout = QVBoxLayout()
        main_layout.addWidget(groupbox)

        self.setLayout(main_layout)
        self.setWindowTitle("CheckBoxes例子")

    def checkbox_state(self, checkbox):
        checkbox1_state = self.checkbox1.text()   ', isChecked='   str(
            self.checkbox1.isChecked())   ', checkState='   str(self.checkbox1.checkState())   'n'
        checkbox2_state = self.checkbox2.text()   ', isChecked='   str(
            self.checkbox2.isChecked())   ', checkState='   str(self.checkbox2.checkState())   'n'
        checkbox3_state = self.checkbox3.text()   ', isChecked='   str(
            self.checkbox3.isChecked())   ', checkState='   str(self.checkbox3.checkState())   'n'
        print(checkbox1_state, checkbox2_state, checkbox3_state)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    main = checkBox()
    main.show()
    sys.exit(app.exec_())

1.4 QComboBox 下拉列表

代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 22:19
# @Author : Michael
# @File : qcomboBox1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QComboBox, QApplication


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

        self.setWindowTitle("combo_box例子")
        self.resize(300, 200)
        layout = QVBoxLayout()

        self.label1 = QLabel("选择语言")

        self.cb = QComboBox()
        self.cb.addItem("C")
        self.cb.addItem("C  ")
        self.cb.addItem("Python")
        self.cb.addItems(["Java", "C#", "PHP"])
        self.cb.currentIndexChanged.connect(self.selectionchange)

        layout.addWidget(self.label1)
        layout.addWidget(self.cb)
        self.setLayout(layout)

    def selectionchange(self):
        self.label1.setText("你选择的语言是:"   self.cb.currentText())
        print('items in the list are:')
        for i in range(self.cb.count()):
            print(f'item {i} = {self.cb.itemText(i)}')
            print(f'current idx {i} selection changed to {self.cb.currentIndex()}')
        print('-'*10)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    combo_box1 = combo_box1()
    combo_box1.show()
    sys.exit(app.exec_())

1.5 QSpinBox 计数器

代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/4 22:43
# @Author : Michael
# @File : spin_box1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSpinBox, QDoubleSpinBox, QApplication
from PyQt5.QtCore import Qt


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

        self.setWindowTitle("SpinBox例子")
        self.resize(300, 100)

        layout = QVBoxLayout()

        self.lb1 = QLabel("当前得分:")
        self.lb1.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.lb1)

        self.spbox = QSpinBox()
        self.spbox.setRange(0, 100)
        self.spbox.setValue(60)
        self.spbox.setSingleStep(2)
        self.spbox.valueChanged.connect(self.value_change)
        layout.addWidget(self.spbox)

        self.lb2 = QLabel("当前平均分:")
        self.lb2.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.lb2)

        self.spbox_double = QDoubleSpinBox()
        self.spbox_double.setRange(0.0, 100.0)
        self.spbox_double.setValue(60.0)
        self.spbox_double.setDecimals(2)
        self.spbox_double.setSingleStep(0.50)
        self.spbox_double.valueChanged.connect(self.value_change1)
        layout.addWidget(self.spbox_double)

        self.setLayout(layout)

    def value_change(self):
        self.lb1.setText("当前得分:"   str(self.spbox.value()))

    def value_change1(self):
        self.lb2.setText("当前平均分:"   str(self.spbox_double.value()))


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    w = spin_box1()
    w.show()
    sys.exit(app.exec_())

1.6 QSlider 滑动条

代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/5 8:20
# @Author : Michael
# @File : slider1.py
# @desc :
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSlider, QApplication
from PyQt5.QtCore import Qt


class slider_demo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("滑块控件")
        self.resize(300, 100)

        layout = QVBoxLayout()

        self.label1 = QLabel('hello michael')
        self.label1.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.label1)

        self.slider1 = QSlider(Qt.Horizontal)  # 水平方向
        self.slider1.setMinimum(10)  # 最小值
        self.slider1.setMaximum(50)  # 最大值
        self.slider1.setSingleStep(3)  # 步长
        self.slider1.setValue(20)  # 当前值
        self.slider1.setTickPosition(QSlider.TicksBelow)  # 刻度位置
        self.slider1.setTickInterval(5)  # 刻度间隔
        layout.addWidget(self.slider1)

        self.slider1.valueChanged.connect(self.value_changed)

        self.setLayout(layout)

    def value_changed(self):
        print('当前滑块的值为:', self.slider1.value())
        size = self.slider1.value()
        self.label1.setFont(QFont('Arial', size))


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    demo = slider_demo()
    demo.show()
    sys.exit(app.exec_())

2. 对话框类

2.1 QDialog

  • 窗口模态 非模态,可以和程序其他窗口交互 窗口模态,程序未处理完当前窗口时,将阻止与父窗口对话 应用程序模态,阻止与任何其他窗口进行交互
代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/5 8:57
# @Author : Michael
# @File : qdialog1.py
# @desc :
from PyQt5.QtWidgets import QMainWindow, QPushButton, QDialog, QApplication
from PyQt5.QtCore import Qt

class qdialog_demo(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QDialog例子")
        self.resize(300, 200)

        self.button = QPushButton("弹出对话框", self)
        self.button.move(50, 50)
        self.button.clicked.connect(self.showdialog)

    def showdialog(self):
        dialog = QDialog()
        btn = QPushButton("ok", dialog)
        btn.move(50, 50)
        dialog.setWindowTitle("提交文件")
        dialog.setWindowModality(Qt.ApplicationModal)
        # 设置应用程序模态,只有关闭弹出窗口后,才能关闭主窗口
        dialog.exec_()
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    main = qdialog_demo()
    main.show()
    sys.exit(app.exec_())

2.2 QMessageBox

有很多常用的,提示,警告,错误,询问,关于等,差别只是样式图标不一样

代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/5 9:30
# @Author : Michael
# @File : qmessagebox1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QPushButton, QMessageBox, QApplication


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

        self.setWindowTitle("QMessageBox1例子")
        self.resize(300, 200)

        self.button1 = QPushButton('点击弹出消息', self)
        self.button1.move(50, 50)
        self.button1.clicked.connect(self.msg)
    def msg(self):
        reply = QMessageBox.warning(self, 'Message标题', '你好,世界!', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            print('点击了Yes')
        else:
            print('点击了No')

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    main = QMessageBox1()
    main.show()
    sys.exit(app.exec_())

2.3 QInputDialog

  • 由一个文本框,两个按钮(OK,Cancel),提交的信息可以被父窗口使用
代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/5 9:49
# @Author : Michael
# @File : input_dialog1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QFormLayout, QPushButton, QLineEdit, QInputDialog, QApplication


class input_dialog1(QWidget):
    def __init__(self):
        super().__init__()
        layout = QFormLayout()

        self.btn1 = QPushButton('获取列表里的选项')
        self.btn1.clicked.connect(self.get_list_item)

        self.lineEdit1 = QLineEdit()
        layout.addRow(self.btn1, self.lineEdit1)

        self.btn2 = QPushButton('获取字符串')
        self.btn2.clicked.connect(self.get_str)
        self.lineEdit2 = QLineEdit()
        layout.addRow(self.btn2, self.lineEdit2)

        self.btn3 = QPushButton('获取整数')
        self.btn3.clicked.connect(self.get_int)
        self.lineEdit3 = QLineEdit()
        layout.addRow(self.btn3, self.lineEdit3)

        self.setLayout(layout)
        self.setWindowTitle('获取输入')
    def get_list_item(self):
        items = ('C', 'C  ', 'Java', 'Python')
        item, ok = QInputDialog.getItem(self, '请选择语言', '语言列表', items, 0, False)
        if ok and item:
            self.lineEdit1.setText(item)
    def get_str(self):
        text, ok = QInputDialog.getText(self, '输入字符串对话框', '请输入字符串')
        if ok:
            self.lineEdit2.setText(text)
    def get_int(self):
        num, ok = QInputDialog.getInt(self, '输入整数对话框', '请输入整数')
        if ok:
            self.lineEdit3.setText(str(num))
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win = input_dialog1()
    win.show()
    sys.exit(app.exec_())

2.4 QFontDialog

  • 字体选择对话框
代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/5 22:18
# @Author : Michael
# @File : qfont_dialog1.py
# @desc :
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QLabel, QFontDialog, QApplication


class fontDialog(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()

        self.fontButton = QPushButton('选择字体')
        self.fontButton.clicked.connect(self.chooseFont)
        layout.addWidget(self.fontButton)

        self.line1 = QLabel('hello michael, 你好啊')
        layout.addWidget(self.line1)

        self.setLayout(layout)
        self.setWindowTitle('字体对话框')
    def chooseFont(self):
        font, ok = QFontDialog.getFont()
        if ok:
            self.line1.setFont(font)
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    ui = fontDialog()
    ui.show()
    sys.exit(app.exec_())

2.5 QFileDialog

  • 打开、保存文件,可以设置文件类型过滤和初始位置
代码语言:javascript复制
# _*_ coding: utf-8 _*_
# @Time : 2022/5/5 22:40
# @Author : Michael
# @File : file_dialog1.py
# @desc :
import time

from PyQt5.QtCore import QDir
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QLabel, QTextEdit, QFileDialog, QApplication


class file_dialog1(QWidget):
    def __init__(self):
        super(file_dialog1, self).__init__()
        layout = QVBoxLayout()

        self.btn = QPushButton('加载图片')
        self.btn.clicked.connect(self.loadfile)
        layout.addWidget(self.btn)

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

        self.btn1 = QPushButton('加载文本文件')
        self.btn1.clicked.connect(self.loadfiles)
        layout.addWidget(self.btn1)

        self.content = QTextEdit() # 文本框
        layout.addWidget(self.content)

        self.setLayout(layout)
        self.setWindowTitle('文件对话框')

    def loadfile(self):
        fname, _ = QFileDialog.getOpenFileName(self, '打开文件', './', '图片文件(*.jpg *.png *gif)')
        self.label.setPixmap(QPixmap(fname))
    def loadfiles(self):
        dlog = QFileDialog()
        dlog.setFileMode(QFileDialog.AnyFile)
        dlog.setFilter(QDir.Files)

        if dlog.exec_():
            fnames = dlog.selectedFiles()
            print(fnames)
            with open(fnames[0], 'r', encoding='utf-8') as f:
                data = f.read()
                self.content.setText(data)
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    ui = file_dialog1()
    ui.show()
    sys.exit(app.exec_())

0 人点赞