MainWindow object has no attribute 'connect

2019-03-01 10:11发布

问题:

I wonder if someone could help me resolve this issue regarding slot connection in PyQt5. The following code snippet will show you what my problem is.

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        path = os.path.join(os.path.dirname(__file__), 'GUI/Main_GUI.ui')
        self.gui = loadUi(path)

        self.gui.button_1.clicked.connect(self.run.this)

    def _connect_my_slots(self, origin):
        self.connect(origin, SIGNAL('completed'), self._show_results)
        self.connect(origin, SIGNAL('error'), self._show_error)

    def run_this(self):
        myThread = LongRunningThing()
        self._connect_my_slots(self.myThread) # THIS IS THE PART THAT CAUSES ERROR

As you can see my MainWindow object is my UI file (from QtDesigner 5) and once I call _connect_my_slots function it throws an error:

AttributError: 'MainWindow' object has no attribute 'connect'

回答1:

You are using the old style signal and slot, which is not longer supported in PyQt5.

The old style:

self.connect(origin, SIGNAL('completed'), self._show_results)

should now be written in the new style:

origin.completed.connect(self._show_results)

For more details, see the documentation on New-style Signal and Slot Support.