我能够结合槽和信号为简单的例子。然而,我想的信号绑定到对象的任何实例 - 说任何QPushButton - 和让槽确定哪些对象是发送者
下面是我的简单结合显式QPushButton实例example:
import sys
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn1 = QPushButton("Button 1", self)
btn1.move(30, 50)
btn2 = QPushButton("Button 2", self)
btn2.move(150, 50)
btn3 = QPushButton("Button 3", self)
btn3.move(30, 150)
btn4 = QPushButton("Button 4", self)
btn4.move(150, 150)
# This code ties the slots and signals together
# clicked is the SIGNAL
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)
btn3.clicked.connect(self.buttonClicked)
btn4.clicked.connect(self.buttonClicked)
self.statusBar()
self.setGeometry(300, 300, 300, 230)
self.setWindowTitle('Event sender')
self.show()
def buttonClicked(self):
sender = self.sender()
self.statusBar().showMessage(sender.text() + ' was pressed firmly')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
该代码不符合PEP8,仅用于示例目的。
答案 0 :(得分:0)
我不知道我是否正确理解了您,但是请尝试以下示例:
import sys
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication
class Example(QMainWindow):
def __init__(self, data):
super().__init__()
self.data = data
self.statusBar()
self.initUI()
def initUI(self):
for b in self.data:
btn = QPushButton(b[0], self)
btn.move(b[1], b[2])
btn.clicked.connect(self.buttonClicked)
def buttonClicked(self):
sender = self.sender()
self.statusBar().showMessage(sender.text() + ' was pressed firmly')
data = [["Button 1", 30, 50],
["Button 2", 150, 50],
["Button 3", 30, 150],
["Button 4", 150, 150] ]
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example(data)
ex.show()
ex.setGeometry(300, 300, 300, 230)
ex.setWindowTitle('Event sender')
sys.exit(app.exec_())