Frage

I am experience with Qt4, but now try to get into the programming of Qt with python.

It works mainly but now I come across a basic python program I did not figure out:

TypeError: setupSignalSlots() takes 1 positional argument but 2 were given

from PyQt4 import QtGui, uic
from PyQt4 import QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        uic.loadUi('MainWindow.ui', self)
        self.show()

        self.setupSignalSlots(self)

    def setupSignalSlots(self):
        self.ui.actionQuit.clicked.connect(OnQuitMainWindow)

    @QtCore.pyqtSlot()
    def OnQuitMainWindow():
        print('quit')
        QApplication.quit()

Besides that problem I wonder if the signal slot code is correct.

War es hilfreich?

Lösung

There are several things wrong with the code you posted.

Firstly, the OnQuitMainWindow slot needs a self argument. However, you do not need to pass this argument explicitly as python will do it automatically. Secondly, when you connect to the slot, you need to access it via self. Finally, quit is not a static method of QApplication, so you need to call it via an instance (e.g. qApp.quit()).

(And one other nit-pick: in python (and Qt, for that matter), it goes against convention to start attribute names with a capital letter).

After making these corrections, your code should look like this:

from PyQt4 import QtGui, uic
from PyQt4 import QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        uic.loadUi('MainWindow.ui', self)
        self.show()

        self.setupSignalSlots()

    def setupSignalSlots(self):
        self.actionQuit.triggered.connect(self.onQuitMainWindow)

    @QtCore.pyqtSlot()
    def onQuitMainWindow(self):
        print('quit')
        QtGui.qApp.quit()

UPDATE:

And one more thing I missed: the way you're using uic.loadUi means that the objects added in Qt Designer will end up as direct attributes of the instance of MainWindow. So it should be self.actionQuit, rather than self.ui.actionQuit. Also, since it appears that this object is a QAction, the signal should be triggered, rather than clicked.

Andere Tipps

You don't need to pass self to a method of a class; it is automatically done for you. Just do self.setupSignalSlots().

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top