python - 基于 Clicked 将单个 Python Def 用于多个 QpushButton

标签 python pyqt

我正在做一个有很多按钮的 GUI。一次有多项选择。

我想知道如何使用 Clicked() 按钮名称作为参数为所有按钮连接一个 Python Def?

最佳答案

使用 QButtonGroup及其 buttonClicked信号。您将获得 idQPushButton 本身。

编辑

一个简单的例子:

import sys
from PyQt4 import QtGui

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        # Arrange buttons horizontally
        buttonLayout = QtGui.QHBoxLayout()

        # QButtonGroup to keep track of buttons
        self.buttonGroup = QtGui.QButtonGroup()

        # Connect the 'buttonClicked' signal 'self.setLabel'
        # There are two overloads for 'buttonClicked' signal: QAbstractButton (button itself) or int (id)
        # Specific overload for the signal is selected via [QtGui.QAbstractButton]
        # Clicking any button in the QButtonGroup will send this signal with the button
        self.buttonGroup.buttonClicked[QtGui.QAbstractButton].connect(self.setLabel)

        for i in range(5): # Let's create 5 button
            button = QtGui.QPushButton('%d' % i)     # make a button
            buttonLayout.addWidget(button)           # add to layout
            self.buttonGroup.addButton(button)       # add to QButtonGroup
            #self.buttonGroup.addButton(button, i)    # You can give an 'id' if you like

        self.label = QtGui.QLabel()  # just to write some output

        # lay everything out
        layout = QtGui.QVBoxLayout()
        layout.addLayout(buttonLayout)
        layout.addWidget(self.label)
        self.setLayout(layout)

    def setLabel(self, button):
        # clicking any button will call this slot 
        # 'button' argument will be the button itself
        # so... let's show its text in the label:
        self.label.setText('You clicked button with text "%s"' % button.text())


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    widget = Widget()
    widget.show()
    app.exec_()

关于python - 基于 Clicked 将单个 Python Def 用于多个 QpushButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12709945/

相关文章:

http - 强制 HTTP 请求不缓存

multithreading - 如何通过调用另一个函数的QThread更新PyQT中的Progressbar

python - PDF 输出不适用于 Pyqt5 和 Python 3.5

python - Pandas 将字典列表(GA 输出)转换为有意义的数据帧

Python套接字ssl连接

python - 在之前的任何地方查找具有字母数字字符的非字母数字字符

python - 从 HTML 数组中提取 4 个字符,Python

python - 在 Python 2.7 中处理超出范围的列表索引

python - Qscrollarea 不显示滚动条并且布局弹出不合适

python - 用于在 librecad 中无限调整大小的绘画的小部件