I want to add my data to a table using pyqt in python. I found that I should use setItem()
function to add data to a QTableWidget
and give it the row and column number and a QTableWidgetItem
. I did it but when I want to display the table, it's completely empty.
Maybe I made a silly mistake but please help me.
Here is my code:
from PyQt4 import QtGui
class Table(QtGui.QDialog):
def __init__(self, parent=None):
super(Table, self).__init__(parent)
layout = QtGui.QGridLayout()
self.led = QtGui.QLineEdit("Sample")
self.table = QtGui.QTableWidget()
layout.addWidget(self.led, 0, 0)
layout.addWidget(self.table, 1, 0)
self.table.setItem(1, 0, QtGui.QTableWidgetItem(self.led.text()))
self.setLayout(layout)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
t = Table()
t.show()
sys.exit(app.exec_())
What you are looking for are the setRowCount()
and setColumnCount()
methods. Call these on the QTableWidget
to specify the number of rows/columns. E.g.
...
self.table = QtGui.QTableWidget()
self.table.setRowCount(5)
self.table.setColumnCount(5)
layout.addWidget(self.led, 0, 0)
layout.addWidget(self.table, 1, 0)
self.table.setItem(1, 0, QtGui.QTableWidgetItem(self.led.text()))
...
This code will make a 5x5 table and display "Sample" in the second row (with index 1) and first column (with index 0).
Without calling these two methods, QTableWidget
would not know how large the table is, so setting the item at position (1, 0) would not make sense.
In case you are unaware of it, the Qt Documentation is detailed and contains many examples (which can easily be converted to Python). The "Detailed Description" sections are especially helpful. If you want more information about QTableWidget
, go here: http://qt-project.org/doc/qt-4.8/qtablewidget.html#details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With