我正在做一个有很多按钮的 GUI。一次有多项选择。
我想知道如何使用 Clicked()
按钮名称作为参数为所有按钮连接一个 Python Def?
最佳答案
使用 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_()
关于python - 基于 Clicked 将单个 Python Def 用于多个 QpushButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12709945/