PyQt4 Tables

Some Python code to create a table with 4 cells and populate it

 

In [8]: a = QTableWidget()
In [9]: a.show()
In [10]: a.columnCount(2)
In [11]: a.setColumnCount(2)
In [12]: a.setRowCount(2)
In [13]: a.setCurrentCell(1,1)
In [16]: b = QTableWidgetItem()
In [17]: b.setText("Hello")
In [18]: a.setItem(0,0,b)
In [32]: d = QTableWidgetItem()
In [33]: d.setText("World")
In [34]: a.setItem(0,1,d)

 

The picture above shows the output from these commands.

The following code was found on the web and automates the process…

 

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore 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)

 

Leave a comment

A WordPress.com Website.

Up ↑