Pyside6 AttributeError in custom signal

50 Views Asked by At

In this minimal code, I'm trying to return a value from an event after pressing a button on the Toolbar.

"connection_established" is the signal connected to connection_status() and connected_button emits the signal

but I receive this error:

self.toolbar_m.connection_established.connect(self.connection_status) AttributeError

I have double-checked many times, and the logic seems correct to me but, of course, something is wrong

from PySide6.QtWidgets import (QMainWindow, QApplication, QToolBar)
from PySide6.QtGui import QAction, QIcon
from PySide6.QtCore import QSize, Signal
from PySide6 import QtCore

QtCore.QDir.addSearchPath('icon', 'icon/')


class ToolBar:
    connection_established = Signal(bool)

    def __init__(self, parent):
        self.parent = parent
        toolbar = QToolBar("toolbar")
        toolbar.setIconSize(QSize(16, 16))

        connect_action = QAction(QIcon('icon:icons8_connect_50.png'), "&Connect", self.parent)
        connect_action.triggered.connect(self.connect_button)
        toolbar.addAction(connect_action)
        toolbar.addSeparator()
        self.parent.addToolBar(toolbar)

    def connect_button(self):
        self.connection_established.emit(True)


class Tele(QMainWindow):
    def __init__(self):
        super(Tele, self).__init__()
        self.toolbar_m = ToolBar(self)
        self.toolbar_m.connection_established.connect(self.connection_status)

    def connection_status(self, connected):
        if connected:
            print("Connected")
        else:
            print("Failed to connect")


if __name__ == "__main__":
    app = QApplication([])
    tele = Tele()
    tele.show()
    app.exec()

It should return the boolean value emitted by connected_button

I am trying to return a value from an event of a toolbar object and use it in the main class Tele()

1

There are 1 best solutions below

1
mahkitah On BEST ANSWER

The Toolbar class is a regular python object. In order to use signals it should inherit from QObject.

from PySide6.QtCore import QSize, Signal, QObject    

class ToolBar(QObject):
    connection_established = Signal(bool)

    def __init__(self, parent):
        super().__init__(parent)
        # rest of the code