[GIS] How to populate QTableWidget via plugin

pyqgispythonqgisqgis-pluginsqt-designer

I am attempting to populate a QTableWidget by adding rows, this is done by the user clicking on the add button:

QTableWidget

I have the following code to try and insert rows but nothing is happening:

def addButton_clicked():
    # objectName for add button = addButton
    # objectName for QTableWidget = tableWidget
    model = dockwidget.tableWidget
    rowCount = self.model.rowCount()
    self.model.insertRows(rowCount, 1)

add_button = self.dockwidget.addButton
add_button.clicked.connect(addButton_clicked)

The Group and Order columns were created from Qt Designer. I am trying to create rows in which the user can select a group from the ToC (in the Group column) and assign an integer (in the Order column). Is something like this possible?

I am open to other ideas.


The following code from @WKT creates a table with columns and x number of rows. I can populate the table with the names of the groups in the ToC. However, I only want to populate the first column. The code I run at the moment populates all columns. Here is the code:

qTable = self.dockwidget.tableWidget
data = []
group1 = root.findGroup('Group1')
group2 = root.findGroup('Group2')
for child in group1.children():
    data.append(child.name())
for child in group2.children():
    data.append(child.name())
nb_row = len(data)
nb_col = 2
qTable.setRowCount(nb_row)
qTable.setColumnCount(nb_col)

for row in range(nb_row):
    for col in range(nb_col):
        item = QTableWidgetItem(str(data[row]))
        qTable.setItem(row,col,item)

qTable.setHorizontalHeaderLabels([u'Column1',u'Column2'])
qTable.resizeColumnsToContents()

QTableWidget

Best Answer

Let me share how it works for me:

self.setWindowTitle(title)

#data = 'Recordset back from postgis'
nb_row = len(data)
nb_col = 2

qTable.setRowCount(nb_row)
qTable.setColumnCount(nb_col)

for row in range (nb_row):
    for col in range(nb_col):
        item = QTableWidgetItem(str(data[row][col]))
        qTable.setItem(row,col,item)

qTable.setHorizontalHeaderLabels([u'Column1',u'Column2'])

qTable.resizeColumnsToContents()
Related Question