1

How to make Headers in the QTableWidget also updated after calling the loadData.

def loadData(self):
    connection = sqlite3.connect('CUSP.db')
    query = "SELECT * FROM ZAYAVITEL"
    result = connection.execute(query)
    self.tableWidget.setColumnCount(6)
    for row_number, row_data in enumerate(result):
        self.tableWidget.insertRow(row_number)
        for column_number, data in enumerate(row_data):
            self.tableWidget.setItem(row_number, column_number, QtWidgets.QTableWidgetItem(str(data)))
    connection.close()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
RoyalGoose
  • 453
  • 9
  • 24
  • Welcome to stackoverflow! Can you please provide more information on your problem? What is that you are trying to achieve? What did you try? What problems have you found so far? Feel free to add these informations by editing your question. – bracco23 Nov 21 '19 at 19:30

1 Answers1

1

You can get the name of the columns using the cursor.description:

def loadData(self):
    self.tableWidget.setColumnCount(0)
    self.tableWidget.setRowCount(0)

    connection = sqlite3.connect("CUSP.db")
    cursor = connection.execute("SELECT * FROM ZAYAVITEL")
    # https://stackoverflow.com/a/7831685/6622587
    names = [description[0] for description in cursor.description]
    self.tableWidget.setColumnCount(len(names))
    self.tableWidget.setHorizontalHeaderLabels(names)

    for i, row_data in enumerate(cursor):
        self.tableWidget.insertRow(i)
        for j, value in enumerate(row_data):
            it = QtWidgets.QTableWidgetItem()
            it.setData(QtCore.Qt.DisplayRole, value)
            self.tableWidget.setItem(i, j, it)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thanks, it works. But how to make sure that every time new rows are not added to the previous ones, and the table just updating the values? – RoyalGoose Nov 21 '19 at 19:52
  • @RoyalGoose If you realize I have used "clear()" that cleans the previous data and places the new information. – eyllanesc Nov 21 '19 at 19:54
  • I noticed, but for some reason, every time after calling this function, I additionally have two more empty lines – RoyalGoose Nov 21 '19 at 20:02
  • 1
    I understood the problem - the .clear() function removes only data from the corresponding cells, but it is necessary to completely clear the entire tableWidget before the operations, i.e. and rows and columns – RoyalGoose Nov 21 '19 at 20:12