Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

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)

6 Comments — feed icon Comments feed for this post


#1 Bastian Weber commented on 2009-06-29:

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 2009-06-29:

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 2009-07-15:

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


#4 Ryan Bales commented on 2009-12-16:

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 2009-12-18:

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 2011-08-22:

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

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode