Search code examples
pythonpyqtqlistwidget

Modify listbox from another class with pyqt


I'm doing a GUI for a database through PyQt and Python. The main window (class Window) has a listbox where I put all my data, for this example I put "The program is working". Furthermore, The other window (class AddWin) help me to add new costumers to the database, but I couldn't modify the listbox from the class Addwin. I have the following code in my program and I would like to clean the listbox from the class AddWin, can you help me? or what is my mistake in the following code?

class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        #Listbox 
        self.lista = QtGui.QListWidget(self)
        self.lista.move(155,221)
        self.lista.resize(855,455)
        self.lista.addItem("The program is working")

class AddWin(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        main = Window()
        main.lista.clear()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

Solution

  • Your mistake is that code doesn't instantiate AddWin anywhere, so lista.clear is never called.

    Your can test it by changing

    window = Window()
    

    to

    window = AddWin()
    

    LAST EDITED 21 / 8 / 2014 12 : 42

    If your want to shard QtGui.QListWidget from QtGui.QMainWindow to QtGui.QDialog, Your can use pass value by reference to QtGui.QDialog.

    Assume your QtGui.QMainWindow must have QtGui.QDialog (Or AddWin);

    class Window(QtGui.QMainWindow):
        def __init__(self, parent=None):
            QtGui.QMainWindow.__init__(self, parent)
            #Listbox 
            self.lista = QtGui.QListWidget(self)
            self.lista.move(155,221)
            self.lista.resize(855,455)
            self.lista.addItem("The program is working")
            self.myAddWin = AddWin(self.lista, self) # <- Pass QListWidget to your class
    
    class AddWin(QtGui.QDialog):
        def __init__(self, refQListWidget, parent=None):
            QtGui.QDialog.__init__(self, parent)
            self.myRefQListWidget = refQListWidget
            self.myRefQListWidget.clear()