1

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

我想知道如何为所有按钮连接单个 Python Def,Clicked()按钮名称为 arg?

4

2 回答 2

6

使用 aQButtonGroup及其buttonClicked信号。你会得到 theid或 theQPushButton本身。

编辑

一个简单的例子:

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_()
于 2012-10-03T13:53:31.507 回答
0

一种简单的方法是创建连接到实际 Qt 事件的小函数——可以是 lambdas 或 functools.partial 返回的对象。这些小函数依次调用您的主回调,传递任意数量的参数:

# coding: utf-8

from PyQt4 import QtCore, QtGui

app = QtGui.QApplication([])
window = QtGui.QWidget()
grid = QtGui.QGridLayout()

def callback(button):
   print button

for x in range(10):
   b = QtGui.QPushButton()
   b.setText(unicode(x))
   grid.addWidget(b, 0, x)
   window.connect(b, QtCore.SIGNAL("clicked()"), (lambda y:lambda: callback(y) )(x))
   b.show()

window.setLayout(grid)
window.show()
app.exec_()

请注意,您必须对作为回调的实际 lambda 使用“封闭 lambda”,以便为每个循环迭代“冻结” x 的值。如果连接调用的表达式只是lambda: callback(x), x 将在按键时进行评估时间,因此 9在这种情况下,对于所有按钮都是 。

callback然而,正如您所要求的那样,主要功能只是一个。

于 2012-10-05T05:18:54.067 回答