1

私はたくさんのボタンでGUIをやっています。一度に複数選択オプション付き。

Clicked()ボタン名を引数としてすべてのボタンに単一の Python Def を接続する方法を知りたいですか?

4

2 に答える 2

6

aQButtonGroupとそのbuttonClicked信号を使用します。idまたはQPushButton自体を取得します。

編集

簡単な例:

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 イベントに接続された小さな関数 (ラムダ、または 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: callback(x)ループ反復ごとにxの値を「フリーズ」するために、コールバックである実際のラムダに「囲むラムダ」を使用する必要があることに注意してください。したがって 9、この場合、すべてのボタンに対して になります。

ただし、主なcallback機能は、あなたが求めたように 1 つだけです。

于 2012-10-05T05:18:54.067 に答える