eddy2k
eddy2k

Reputation: 119

Using the automatic connect slots by name

A while ago, I had been using (in a given framework at work) the automatic connect slots by name feature in Qt4, with a decorator. Something like this:

self.button1 = QtWidgets.QPushButton("Click me!")
...
@QtCore.Slot()
def on_button1_clicked(self):
     # whatever the method does...

instead of this:

self.button1 = QtWidgets.QPushButton("Click me!")
self.button1.clicked.connect(self.handle_button)
...
def self.handle_button(self):
    # whatever the method does...

Now I am not able to make it work with PySide2 (Qt-5.12). What I am missing here to make it work?

import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)

        self.hello = ["Hallo Welt", "Hola Mundo"]

        self.button1 = QtWidgets.QPushButton("Click me!")
        self.text = QtWidgets.QLabel("Hello World")
        self.text.setAlignment(QtCore.Qt.AlignCenter)

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.text)
        self.layout.addWidget(self.button1)
        self.setLayout(self.layout)

        QtCore.QMetaObject.connectSlotsByName(self)

        #self.button1.clicked.connect(self.on_button1_clicked)

    @QtCore.Slot()
    def on_button1_clicked(self):
        self.text.setText(random.choice(self.hello))


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

widget = MyWidget()
widget.show()

sys.exit(app.exec_())

Upvotes: 3

Views: 2254

Answers (1)

ekhumoro
ekhumoro

Reputation: 120598

The connectSlotsByName feature is usually used with Qt Designer files. When those files are converted with the uic tool, a lot of boiler-plate code gets added. This includes setting the object-name, which is required when connecting slots by name:

self.button1 = QtWidgets.QPushButton("Click me!")
self.button1.setObjectName('button1')

Obviously, the object-name must match the name used in the slot.

Upvotes: 1

Related Questions