SaltyCrane Blog — Notes on JavaScript and web development

QTableWidget Example using Python 2.4, QT 4.1.4, and PyQt

QTableWidget Example using Python 2.4, QT 4.1.4, and PyQt
import sys
from Qt import *

lista = ['aa', 'ab', 'ac']
listb = ['ba', 'bb', 'bc']
listc = ['ca', 'cb', 'cc']
mystruct = {'A':lista, 'B':listb, 'C':listc}

class MyTable(QTableWidget):
    def __init__(self, thestruct, *args):
        QTableWidget.__init__(self, *args)
        self.data = thestruct
        self.setmydata()
        
    def setmydata(self):
        n = 0
        for key in self.data:
            m = 0
            for item in self.data[key]:
                newitem = QTableWidgetItem(item)
                self.setItem(m, n, newitem)
                m += 1
            n += 1

def main(args):
    app = QApplication(args)
    table = MyTable(mystruct, 5, 3)
    table.show()
    sys.exit(app.exec_())
    
if __name__=="__main__":
    main(sys.argv)

Comments


#1 Bastian Weber commented on :

Thank you for this example. It saved me quite some searching time.

(.. On my machine I had to alter "from Qt import *" into "from PyQt4.QtGui import *")


#2 Eliot commented on :

Bastian, yes I think from PyQt4.QtGui import * is the correct import statement now. I think from Qt import * was the old way. Thanks for your comment.


#3 Yuri commented on :

How can I copy and pasty all the data from the whole table?


#4 Ryan Bales commented on :

Fantastic examples you have here. One thing I would do differently is to make use of enumerate() to index your for loops.

I would rework the above like...

def setmydata(self):
    for n, key in enumerate(self.data):
        for m, item in enumerate(self.data[key]):
            newitem = QTableWidgetItem(item)
            self.setItem(m, n, newitem)

#5 Eliot commented on :

Ryan, Thanks. I agree your modification is much better. I learned about enumerate a couple years after I originally wrote this. (Also, I added one blank line in your comment before your code block so the formatting would come out correctly.)


#6 Nader commented on :

A Question: How to add "Cut & Paste" to QTableWidget?