[PyQt] How to update the timer automatically in the tree view - Model/View programming

Hans-Peter Jansen hpj at urpla.net
Wed Mar 16 13:51:39 GMT 2011


On Wednesday 16 March 2011, 13:21:21 vijay swaminathan wrote:
> Hi All,
>
> I'm a new bie to model/view programming and have just written a small
> script as attached.
>
> For some reasons the time is not getting updated on the tree view. it
> gets updated only when I select that element on that tree. I did a
> searched and I was told that I got to use signal / slot mechanism to
> get the timer updated automatically.
>
> I did give it a try but did not work. can someone pls help me on
> where exactly I went wrong.

First, you missed to start the timer. Next, just holding a parent
relationship to the timer seems not enough to keep the signal/slot
connection alive. Last, let's keep the M/V concept intact.

@Phil: for some reason, quitting this script triggers:

QObject::startTimer: QTimer can only be used with threads started with QThread
QObject::startTimer: QTimer can only be used with threads started with QThread

I've noticed this on other occasions, too. I guess, it's due to the 
undefined destruction sequence of the python GC, where the timer 
fires, but the signal handler was partly destructed already...

Do you have an idea on how to avoid that?

Pete

python: 2.6
sip: 4.12.1
qt4: 4.6.3
pyqt4: snapshot-4.8.4-278054fd857c


import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *


class TimeTreeView(QAbstractListModel):
    def __init__(self, data, parent=None):
        super(TimeTreeView, self).__init__(parent)

        self.data = data
        print self.data
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.timerhit)
        self.timer.start()

    def rowCount(self, parent):
        return len(self.data)

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole and index.isValid():
            return self.data[index.row()]

    def setData(self, index, value, role = Qt.EditRole):
        if role != Qt.EditRole:
            return False
        row = index.row()
        if row != 2:
            return False
        self.data[row] = value
        self.dataChanged.emit(index, index)

    def timerhit(self):
        self.setData(self.createIndex(2, 0), QTime().currentTime().toString())


def main():
    myapp = QApplication(sys.argv)

    data = ['Time1', 'Time2', 'Time3']

    model = TimeTreeView(data)
    
    tree_view = QTreeView()
    tree_view.show()
    tree_view.setModel(model)

    myapp.exec_()


if __name__ == '__main__':
    main()


More information about the PyQt mailing list