PyQt4: example of TableWidget usage

The following simple example (inspired by saltycrane example shows how to build a simple application that pops up a table with PyQt4 and its TableWidget class.

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
 
data = {'col1':['1','2','3'], 'col2':['4','5','6'], 'col3':['7','8','9']}
 
class MyTable(QTableWidget):
    def __init__(self, data, *args):
        QTableWidget.__init__(self, *args)
        self.data = data
        self.setmydata()
        self.resizeColumnsToContents()
        self.resizeRowsToContents()
 
    def setmydata(self):
 
        horHeaders = []
        for n, key in enumerate(sorted(self.data.keys())):
            horHeaders.append(key)
            for m, item in enumerate(self.data[key]):
                newitem = QTableWidgetItem(item)
                self.setItem(m, n, newitem)
        self.setHorizontalHeaderLabels(horHeaders)
 
def main(args):
    app = QApplication(args)
    table = MyTable(data, 5, 3)
    table.show()
    sys.exit(app.exec_())
 
if __name__=="__main__":
    main(sys.argv)
Please follow and like us:
This entry was posted in Python and tagged , , . Bookmark the permalink.

3 Responses to PyQt4: example of TableWidget usage

  1. Lucho says:

    Thanks!!!

  2. Carver says:

    Posted 3 1/2 years ago, and I still found this very helpful <3

  3. Craig Matthews says:

    Thank you, very helpful.

Leave a Reply

Your email address will not be published.