This is my third project using PySide and I came across an unusual error when trying to use custom Signals and Slots. Below is a variation of what I am working on that is giving me the AttributeError. I have used a similar syntax for other projects with no issues, so any help is appreciated. I do understand per the error that I am trying to connect a function to a slot, however if I use the @Signal decorator I receive a separate error basically saying that I cannot use it.
JavaScript
x
54
54
1
from PySide2.QtWidgets import *
2
from PySide2.QtGui import *
3
from PySide2.QtCore import *
4
import sys
5
6
7
class TestSignal(QObject):
8
signal = Signal(float)
9
10
def __init__(self):
11
QObject.__init__(self)
12
13
def changed(self, test_value: float):
14
self.signal.emit(test_value)
15
16
17
class Main(QMainWindow):
18
def __init__(self):
19
QMainWindow.__init__(self)
20
21
self.signal = TestSignal()
22
self.signal.changed.connect(self.test_slot) # this is where the error occurs
23
24
self.central_widget = QWidget()
25
26
self.go_button = QPushButton("Emit")
27
self.go_button.clicked.connect(self.emit_signal)
28
29
self.change_label = QLabel("Push Button")
30
31
self.test_layout = QVBoxLayout()
32
self.test_layout.addWidget(self.change_label)
33
self.test_layout.addWidget(self.go_button)
34
self.setCentralWidget(self.central_widget)
35
36
self.central_widget.setLayout(self.test_layout)
37
38
self.show()
39
40
@Slot(float)
41
def test_slot(self, test_value):
42
self.change_label.setText("Emitted Signal successcully")
43
44
def emit_signal(self):
45
self.signal.changed()
46
47
48
if __name__ == '__main__':
49
app = QApplication(sys.argv)
50
window = Main()
51
52
app.exec_()
53
sys.exit(0)
54
Advertisement
Answer
The signal is called “signal”, “changed” is just a method where the signal is emitted. Recommendation: Use more descriptive names to avoid this type of confusion
JavaScript
1
36
36
1
class TestSignal(QObject):
2
signal = Signal(float)
3
4
def changed(self, test_value: float):
5
self.signal.emit(test_value)
6
7
8
class Main(QMainWindow):
9
def __init__(self):
10
QMainWindow.__init__(self)
11
12
self.signal = TestSignal()
13
self.signal.signal.connect(self.test_slot)
14
15
self.central_widget = QWidget()
16
17
self.go_button = QPushButton("Emit")
18
self.go_button.clicked.connect(self.emit_signal)
19
20
self.change_label = QLabel("Push Button")
21
22
self.test_layout = QVBoxLayout()
23
self.test_layout.addWidget(self.change_label)
24
self.test_layout.addWidget(self.go_button)
25
self.setCentralWidget(self.central_widget)
26
27
self.central_widget.setLayout(self.test_layout)
28
29
self.show()
30
31
@Slot(float)
32
def test_slot(self, test_value):
33
self.change_label.setText("Emitted Signal successcully {}".format(test_value))
34
35
def emit_signal(self):
36
self.signal.changed(5.0)