Το
QTableWidget είναι ένα widget της PyQt4 που μοιάζει με spreadsheet.
Ο constructor του παίρνει 2 integers που του λένε ποσες σειρές και πόσες στήλες θα περιέχει.
Tα αντικείμενα που μπαίνουν μέσα του πρέπει να είναι τύπου QTableWidgetItem
To snippet που ακολουθεί δείχνει πως μπορούμε να το χρησιμοποιήσουμε για να παρουσιάσουμε κάποια δεδομενα σε μορφή πίνακα.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Import necessary libraries
import sys
import PyQt4.QtGui as QtGui
# The data that we want to present. Suppose that they are read from an sqlite
# database.
all_items = [
[1, "O Kostas", "Kostas Papadopoulos", 000000000, "A Athina", "Address 1", "210.000.00.00"],
[2, "O Mitsos", "Mitsos Papadopoulos", 000000001, "A Athina", "Address 2", "210.000.00.01"],
[3, "O Tasos", "Tasos Papadopoulos", 000000002, "A Athina", "Address 3", "210.000.00.03"],
[4, "O Manos", "Manos Papadopoulos", 000000003, "A Athina", "Address 4", "210.000.00.04"]]
class MyTable(QtGui.QTableWidget):
def __init__(self, data):
"""
Subclassing the QTableWidget.
"""
# The syntax of the SuperClass constructor is the following:
#
# __init__ (self, int rows, int columns, QWidget parent = None)
#
# So we calculate the number of rows and columns and then we call it.
number_of_rows = len(data)
number_of_cols = len(data[0])
super(MyTable, self).__init__(number_of_rows, number_of_cols)
# Pretty obvious I believe.
self.data = data
self.setdata()
self.setMinimumSize(700,300)
def setdata(self):
"""
Reads the item of the data, one by one and row by row.
Each item is converted into a string. For some reason, numbers are not
displayed by QTableWidgets.
A new_item is constructed as a QTableWidgetItem and then it is placed
at (row=i, column=j) in QTableWidget by the setItem method.
"""
for i, row in enumerate(self.data):
for j, item in enumerate(row):
item = str(item)
new_item = QtGui.QTableWidgetItem(item)
self.setItem(i, j, new_item)
def main(args):
app = QtGui.QApplication(args)
table = MyTable(all_items)
table.show()
sys.exit(app.exec_())
if __name__=="__main__":
main(sys.argv)