1

I'm building a pyqt Qwidget with multiple QcomboBox in which the user can add items at will. But I also want to give the user the option to delete any of the items by clicking a QPushbutton.

Because I can't know in advance which comboBox and item the user will want to delete, I created an event filter to find which object is being activated, and which item is being selected.

The code below works as expected, but the function printevent is being called an increasingly number of times, which will eventually turn my program very slow.

I tried to define @QtCore.pyqtSlot() to no avail.

What did I do wrong?

My code (for this example, I'm only showing one of the ComboBoxes):

from PyQt4 import QtCore, QtGui
import sys, os, json

class Ui_MainWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Ui_MainWindow,self).__init__(parent=parent)

        ### MAIN WINDOW ####
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1016, 790)
        MainWindow.move(200,30)

        self.centralwidget = QtGui.QWidget()

        self.gridLayout_2 = QtGui.QGridLayout()
        self.gridLayout_2.setVerticalSpacing(0)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))

        self.comboBox_nationality = QtGui.QComboBox(self.centralwidget)
        self.comboBox_nationality.setEditable(True)
        self.gridLayout_2.addWidget(self.comboBox_nationality, 1, 0, 1, 1)

        self.comboBox_nationality.installEventFilter(self)

    def eventFilter(self,obj, event):
        if  event.type() == QtCore.QEvent.FocusIn:
            objt=str(obj.objectName())

            exec('self.' + objt + '.activated[str].connect(self.printevent)')
        return super(Ui_MainWindow,self).eventFilter(obj,event)

    @QtCore.pyqtSlot(QtCore.QString) # Doesn't change anything 
    @QtCore.pyqtSlot() # TypeError: printevent() takes exactly 2 arguments (1 given)   

    def printevent(self,item):
        print item


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ex = Ui_MainWindow()
    ex.__init__(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
Elcook
  • 165
  • 2
  • 10
  • Why don't you just connect all the signals in the normal way when the combo-boxes are created in `__init__`? The event-filter doesn't achieve anything (even if it worked properly). Use `combo = self.sender()` in the slot to get the widget that sent the signal. – ekhumoro Sep 15 '17 at 17:17
  • You are absolutely right, I was complicating waaayyy to much. combo =self.sender() does exactly what I wanted. Thank you! – Elcook Sep 16 '17 at 11:33

0 Answers0