ZetCode

PyQt QPushButton

最后修改于 2023 年 8 月 24 日

在本文中,我们将展示如何使用 QPushButton 部件。

请访问 Advanced PyQt5 电子书,阅读 PyQt5 教程,或查看 所有 PyQt 教程列表。

PyQt QPushButton

QPushButton 是一个当用户点击它时执行操作的部件。一个 QPushButton 可以显示文本和图标。

当通过鼠标、空格键或键盘快捷键激活时,按钮会发出 clicked 信号。

QPushButton 示例

以下示例创建了一个退出按钮。当我们点击该按钮时,应用程序将终止。

quit_button.py
#!/usr/bin/python

import sys
from PyQt6.QtWidgets import QWidget, QPushButton, QApplication, QVBoxLayout
from PyQt6.QtCore import Qt


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        vbox = QVBoxLayout()

        qbtn = QPushButton('Quit', self)
        vbox.setAlignment(Qt.AlignmentFlag.AlignLeft)
        qbtn.clicked.connect(QApplication.instance().quit)

        vbox.addWidget(qbtn)
        vbox.addStretch(1)

        self.setLayout(vbox)

        self.setGeometry(400, 400, 400, 300)
        self.setWindowTitle('Quit button')
        self.show()


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

QPushButton 被放置在一个 QVBoxLayout 中。

qbtn = QPushButton('Quit', self)

创建了 QPushButton。该按钮只显示文本。

qbtn.clicked.connect(QApplication.instance().quit)

我们将 clicked 信号连接到 QApplicationquit 函数。

QPushButton
图:QPushButton

带图标的 QPushButton

QPushButton 可以显示带图标的文本。

icons.py
#!/usr/bin/python

import sys
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QWidget, QPushButton, QApplication, QHBoxLayout


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        hbox = QHBoxLayout()

        btn1 = QPushButton(QIcon('exit.png'), 'Exit', self)
        btn2 = QPushButton(QIcon('save.png'), 'Save', self)
        btn3 = QPushButton(QIcon('new.png'), 'New', self)

        hbox.addWidget(btn1)
        hbox.addWidget(btn2)
        hbox.addWidget(btn3)
        hbox.addStretch(1)

        self.setLayout(hbox)

        self.move(300, 300)
        self.setWindowTitle('Icons')
        self.show()


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

在此示例中,我们有三个按钮。我们将一个 QIcon 作为第一个参数传递给 QPushButton

QPushButton with icon
图:带图标的 QPushButton

QPushButton 切换按钮

切换按钮是处于特殊模式下的 QPushButton。它是一个有两种状态的按钮:按下和未按下。我们通过点击它来在这两种状态之间切换。切换按钮通过 setCheckable 函数创建。

toggle_button.py
#!/usr/bin/python


from PyQt6.QtWidgets import (QWidget, QPushButton, QHBoxLayout, QVBoxLayout,
                             QFrame, QApplication)
from PyQt6.QtGui import QColor
import sys


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        hbox = QHBoxLayout()
        vbox = QVBoxLayout()

        self.col = QColor(0, 0, 0)

        redb = QPushButton('Red', self)
        redb.setCheckable(True)

        redb.clicked.connect(self.setColor)

        greenb = QPushButton('Green', self)
        greenb.setCheckable(True)

        greenb.clicked.connect(self.setColor)

        blueb = QPushButton('Blue', self)
        blueb.setCheckable(True)

        blueb.clicked.connect(self.setColor)

        hbox.addWidget(redb)
        hbox.addWidget(greenb)
        hbox.addWidget(blueb)

        self.square = QFrame(self)
        self.square.setFixedSize(180, 180)
        self.square.setStyleSheet("QWidget { background-color: %s }" %
                                  self.col.name())

        vbox.addLayout(hbox)
        vbox.addWidget(self.square)

        self.setLayout(vbox)

        self.move(300, 300)
        self.setWindowTitle('Toggle button')
        self.show()

    def setColor(self, pressed):

        source = self.sender()

        if pressed:
            val = 255
        else:
            val = 0

        if source.text() == 'Red':
            self.col.setRed(val)
        elif source.text() == 'Green':
            self.col.setGreen(val)
        else:
            self.col.setBlue(val)

        self.square.setStyleSheet('QFrame { background-color: %s }' %
                                  self.col.name())


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

该示例包含三个切换按钮和一个 QWidget。我们将 QWidget 的背景颜色设置为黑色。切换按钮可以切换颜色值中的红色、绿色和蓝色部分。背景颜色取决于哪些切换按钮被按下。

self.col = QColor(0, 0, 0)

这是初始的黑色颜色值。

redb = QPushButton('Red', self)
redb.setCheckable(True)

要创建一个切换按钮,我们创建一个 QPushButton,然后通过调用 setCheckable 函数使其可选中。

redb.clicked.connect(self.setColor)

我们将 clicked 信号连接到我们自定义的函数。

source = self.sender()

我们使用 sender 函数获取被切换的按钮。

if source.text() == 'Red':
    self.col.setRed(val)

如果它是红色按钮,我们就相应地更新颜色的红色部分。

self.square.setStyleSheet('QFrame { background-color: %s }' %
    self.col.name())

我们使用样式表来更改背景颜色。样式表通过 setStyleSheet 函数进行更新。

QPushButton in toggle mode
图:切换模式下的 QPushButton

在本文中,我们介绍了 PyQt 的 QPushButton 部件。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已经创作了超过 1400 篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出所有 PyQt 教程