[PyQt] How to update an QAbstactTableModel

despen at verizon.net despen at verizon.net
Tue Dec 8 22:34:36 GMT 2009

Simon Hibbs <simon.hibbs at gmail.com> writes:

>> I've written a stock portfolio tracker in pyqt4. The main window which
>> is a QAbstractTableModel has an Update button. When I click it, the
>> program gets new stock prices and updates the data in the table.
>> My problem is that the data displayed in the table doesn't update until
>> the window loses and regains focus....
> If you're loading the data into the database directly using SQL, then QT
> won't be aware of the change. You could tryusing
> QSqlRelationalTableModel.setData() to push the data into the model. It's
> described here:

Thanks for the reply.

I'm not using SQL.
I get updated prices for stocks from Yahoo.  That changes the stuff
being displayed.

The init method is like this:

class MyTableModel(QAbstractTableModel): 
    def __init__(self, datain, headerdata, parent=None, *args): 
        QAbstractTableModel.__init__(self, parent, *args) 
        self.arraydata = datain
        self.headerdata = headerdata

and the init method gets called like this;

        tm = MyTableModel(self.tabledata, header, self) 

My problem is getting new data from tabledata into the display.
The init above works but later on from a shortcut I
tabledata and do:


and changeData does:

    def changeData(self, datain):
        self.arraydata = datain

I also tried changing the word "Layout" to "Data" but neither
causes the table to update after the shortcut.

If I unfocus and focus the window it does update.
So I think I'm getting the data into the table, it's just not
repainting itself.

The data method for the table looks like this:

    def data(self, index, role): 
        if not index.isValid(): 
            return QVariant() 
        elif role == Qt.TextAlignmentRole: 
            if (index.column() == 0):
                return Qt.AlignLeft
            return Qt.AlignRight
        elif role == Qt.BackgroundColorRole:
            symbol = self.arraydata[index.row()][0]
            if symbol == "$" :
                return QVariant(QColor(0xEE, 0xFF, 0xEE))
            shares = self.arraydata[index.row()][1]
            if shares == '0' :
                return QVariant(QColor('wheat'))
            if symbol[0] == '^' :
                return QVariant(QColor(0xEE, 0xEE, 0xF5))
            if index.row() == len(self.arraydata) - 1 :
                return QVariant(QColor('lightgray'))
            return QVariant()
        elif role == Qt.TextColorRole:
            content = self.arraydata[index.row()][index.column()]
            if content != 0 and str(content)[0] == '-' :
                return QVariant(QColor('red'))
            return QVariant() 
        elif role != Qt.DisplayRole: 
            return QVariant() 
        return QVariant(self.arraydata[index.row()][index.column()]) 

More information about the PyQt mailing list