Search code examples
pythonpyside2qt-signalsslot

PySide2 doesn't behave like PySide when the slot function has a default argument=None


The code below works fine with PySide, but not with PySide2:

when the action is triggered (Ctrl+S), the function saveResults is called with filename=False, not None as I would expect (and as was the case with PySide: you can test by switching the import statements).

I'm wondering whether there has been a change in behavior,
or something to fix in my code? (I know I can do with the lambda trick, I'm more curious if it's the Slot syntax or the connect that needs precision).

import sys

# PySide2 won't pop up the QFileDialog
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2.QtCore import Slot

# # PySide works fine:
# from PySide.QtGui import *
# from PySide.QtCore import Slot


class MyWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.fileMenu = self.menuBar().addMenu("&File")
        act = QAction("Save results...", self)
        act.triggered.connect(self.saveResults)  # <--- should call saveResults(None)
        #act.triggered.connect(lambda: self.saveResults(None))   # fixes the issue
        act.setShortcuts([QKeySequence.Save])
        self.fileMenu.addAction(act)

    @Slot()
    def saveResults(self, filename=None):
        print ('Calling saveResults, filename is', filename)
        if filename is None:
            (filename, selectedfilter) = QFileDialog.getSaveFileName(self,"Save results as ", ".", "NPY Files (*.npy);;Image files (*.png *.tif *.tiff *.bmp);;All files (*)")
            # ... exit if cancel clicked
        # finally save the file:
        print('Saving', filename)


qt_app = QApplication(sys.argv)
app = MyWindow()
app.show()
qt_app.exec_()


Solution

  • It seems to be a bug, a workaround is to make the connection through keyword triggered:

    # ...
    self.fileMenu = self.menuBar().addMenu("&File")
    act = QAction("Save results...", self, triggered=self.saveResults)
    act.setShortcuts([QKeySequence.Save])
    self.fileMenu.addAction(act)
    # ...