我正在做一個有很多按鈕的GUI。一次有多個選擇選項。使用單一的Python Def爲多點QpushButton基於點擊
我想知道如何與Clicked()
按鈕名稱連接一個Python防守對所有按鈕的ARG?
我正在做一個有很多按鈕的GUI。一次有多個選擇選項。使用單一的Python Def爲多點QpushButton基於點擊
我想知道如何與Clicked()
按鈕名稱連接一個Python防守對所有按鈕的ARG?
使用QButtonGroup
及其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_()
一個簡單的方法是創建小功能 - 其可以是lambda表達式,或物體通過functools.partial作爲返回 - 被連接到所述實際的Qt事件。這些小功能依次調用你的主要的回調,傳遞儘可能多的參數,只要你喜歡:
# 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_()
通知您必須使用「封閉拉姆達」在實際工作拉姆達這是回調, 以爲每個循環迭代「凍結」x的值。如果連接調用的表達式僅在lambda: callback(x)
,x將在按鍵時間被評估,並且因此將是9
,在這種情況下,對於所有按鈕。
主要callback
功能,但是,僅僅是一個,就像你問。
Imho你的lambda表達式不是很有說服力。 'lambda x:callback(x,a,b)'其中'a'和'b'是來自lambda定義的全局或局部範圍的變量。 –
而你的lambda也可以很容易地寫成'lambda:callback(x)'。 –
'lambda y = x:callback(y)'將_freeze_ x的值。不需要外部'lambda'。雖然這有效,但由於方便和更多選項,我仍然會使用'QButtonGroup'。 – Avaris
謝謝Avaris ..你能給出一個帶有幾個按鈕和單個回調函數的示例代碼嗎? becoz即時通訊Qt – rishis3d
@ rishis3d:當然,我已經用一個例子編輯了我的答案(希望對你有足夠的評論來弄清楚)。 – Avaris
感謝您的示例代碼..工作正常..如何ABT多次選擇一次使用「Shift」鍵?它可能是非常有用的我的GUI ..即時通訊做一個字符CTRL瑪雅選擇GUI – rishis3d