GUI (PyQt) & thread problem

Kristian Nylund krnylund at msn.com
Sun Feb 24 13:51:40 CET 2002


Hello

Can someone tell me what the problem is with the following program, as it 
hangs. I'm pretty sure there's some inherent design-flaw involved, but
I'm not familiar enough with threads or GUI-programming to know what it 
could be.

I've also tried modyfing the program to use PYSIGNALs instead of passing the
caller to the thread, but the results were the same.

tia,

Kristian

#!/usr/bin/env python
from qt import *
from threading import *
from time import sleep

class Worker(Thread):

    def __init__(self, mw):
        Thread.__init__(self)
        # Take calling object as attribute
        self.mw = mw
        self.counter = 0

    def run(self):
        # Add 5 objects the the ListView
        while self.counter < 5:
            # Invoke method from calling object
            self.mw.addRow('val%d' % self.counter)
            self.counter = self.counter + 1
            sleep(1)
        # Remove the 5 objects from the ListView in order
        while self.counter > 0:
            # Invoke method from calling object
            self.mw.delRow('val%d' % self.counter)
            self.counter = self.counter - 1
            sleep(1)
        return

class MainWin(QMainWindow):

    def __init__(self,parent = None,name = None,fl = 0):
        QMainWindow.__init__(self,parent,name,fl)
        self.setName("Form1")
        self.resize(200,250)
        self.setCentralWidget(QWidget(self,"qt_central_widget"))

        self.ListView1 = QListView(self.centralWidget(),"ListView1")
        self.ListView1.addColumn("Column 1")
        self.ListView1.setGeometry(QRect(20,10,150,200))

        self.worker = Worker(self)
        self.worker.start()
        # If the following line is omitted, the program will
        # hang when trying to add the first object to the ListView
        QListViewItem(self.ListView1, ' ')

    def addRow(self, val):
        QListViewItem(self.ListView1, val)

    def delRow(self, val):
        # This is where it hangs
        print "Hang..."
        item = self.ListView1.findItem(val, 0)
        print "This won't be printed."
        self.ListView1.takeItem(item)
        del(item)

if __name__ == "__main__":
    a = QApplication(sys.argv)
    w = MainWin()
    a.setMainWidget(w)
    w.show()
    a.exec_loop()



More information about the Python-list mailing list