我想询问是否可以使用信号/插槽传输如下信息:“点击此按钮?”
我在这里准备了一些代码......
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Worker(QObject):
def __init__(self, parent=None):
super(Worker, self).__init__(parent)
@pyqtSlot(str, str, int, add_one_more_signal)
def onJob(self, strA, strB, int1, add_one_more_signal):
print(strA, strB, int1)
# if the signal detects the btn1 was clicked:
# print("button 1 is clicked; button 2 is not clicked")
# if the signal detects the btn2 was clicked:
# print("button 1 is not clicked; button 2 is clicked")
class MyApp(QWidget):
signal = pyqtSignal(str, str, int, add_one_more_signal)
def __init__(self, parent= None):
super(MyApp, self).__init__(parent)
self.initUI()
def initUI(self):
self.btn1 = QPushButton("start 1", self)
self.btn2 = QPushButton("start 2", self)
self.btn1.clicked.connect(self.start)
self.btn2.clicked.connect(self.start)
self.layout = QVBoxLayout()
self.layout.addWidget(self.btn1)
self.layout.addWidget(self.btn2)
self.setLayout(self.layout)
self.show()
def start(self):
otherClass = Worker()
self.signal.connect(otherClass.onJob)
self.signal.emit("foo", "baz", 10, self.btn1.clicked(True) or self.btn2.clicked(True)) # How to write this line?
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
请不要理解我错了。我非常了解如何实现程序目的。我只是想知道,如何传输信号,检测是否点击了按钮。 - 说实话,我也想知道Signal + Slot的功能。
在我的代码中有两个按钮。它们共享相同的子功能。 (正如我所提到的,仅针对这个问题。)当单击其中一个时,三个参数从MyApp-Class传输到Worker-Class。
现在我想介绍第四个参数,我也在上面的代码中写了这个参数。第四个参数只执行一个作业,即发送信息,是否单击按钮。
所以我的问题是:如果可行,如何编写代码?
这应该是一个初学者愚蠢的问题。但我感谢您的任何提示+评论+回复。谢谢!
答案 0 :(得分:2)
一种可能的解决方案是发送显示按钮的文本,为此第四个参数必须是str
类型,以获取发出我们使用的信号sender()
的对象,在这种情况下sender()
将是被按下的对象,然后我们得到文本并发送它。
class Worker(QObject):
def __init__(self, parent=None):
super(Worker, self).__init__(parent)
@pyqtSlot(str, str, int, str)
def onJob(self, strA, strB, int1, text):
print(strA, strB, int1)
if text == "start 1":
print("button 1 is clicked")
elif text == "start 2":
print("button 2 is clicked")
class MyApp(QWidget):
signal = pyqtSignal(str, str, int, str)
def __init__(self, parent= None):
super(MyApp, self).__init__(parent)
self.initUI()
def initUI(self):
self.btn1 = QPushButton("start 1", self)
self.btn2 = QPushButton("start 2", self)
self.btn1.clicked.connect(self.start)
self.btn2.clicked.connect(self.start)
self.layout = QVBoxLayout()
self.layout.addWidget(self.btn1)
self.layout.addWidget(self.btn2)
self.setLayout(self.layout)
self.show()
def start(self):
otherClass = Worker()
btn = self.sender()
self.signal.connect(otherClass.onJob)
self.signal.emit("foo", "baz", 10, btn.text())