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)
Related posts
- PyQt: How to pass arguments while emitting a signal — posted 2008-01-29
- PyQt4 QItemDelegate example with QListView and QAbstractListModel — posted 2008-01-23
- How to install pyqt4 on ubuntu linux — posted 2008-01-15
- Python PyQt Tab Completion example — posted 2008-01-04
- How to capture the Tab key press event with PyQt 4.3 — posted 2008-01-03
- PyQt 4.3 Simple QAbstractListModel/ QlistView example — posted 2008-01-03
Comments
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 *")
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.
How can I copy and pasty all the data from the whole table?
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)
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.)
A Question: How to add "Cut & Paste" to QTableWidget?