I've been able to use QTableWidget and QTableWidgetItem to populate info from our database into a QTableWidget based on the text returned in the search bar. While I'm able to get the searched item to populate all the info into a tablewidget, I am not able to continuely add products from the search bar into the tablewidget. Instead the result is just being overrode and replaced. Here's an example of my code.
# Defines Search Bar Button
def search_Bar(self):
searchFor = self.searchBar.text()
#print(searchFor)
searchQ = c.execute(" SELECT * FROM databasetable WHERE title LIKE ('%' || ? || '%') ", (searchFor,))
self.tableWidget.setRowCount(0)
for row_number, row_data in enumerate(searchQ):
self.tableWidget.insertRow(row_number)
for column_number, data in enumerate(row_data):
self.tableWidget.setItem(row_number, column_number, QTableWidgetItem(str(data)))
The above code will yield me the desired results however when I try to add multiple items to the QTableWidget it overwrites the previously selected item.
Is it possible to setItem without having it override the previous selection? I'd like to be able to create a table of the desired search results. We'd like the option to clear the table as well if needed.
In order to append search results to the table without overwriting the previous table content, just don't call setRowCount(0)
before adding items and use the current rowCount()
as the row_number
:
# Append search results to table
def search_Bar(self):
searchFor = self.searchBar.text()
searchQ = c.execute(" SELECT * FROM databasetable WHERE title LIKE ('%' || ? || '%') ", (searchFor,))
for row_data in searchQ:
# insert new row at the end of the tableWidget
row_number = self.tableWidget.rowCount()
self.tableWidget.insertRow(row_number)
for column_number, data in enumerate(row_data):
self.tableWidget.setItem(
row_number, column_number, QTableWidgetItem(str(data)))
If you want to clear the table (e.g. by clicking a "Clear Table" button), you can call the following function:
# Clear the table
def clear_table(self):
self.tableWidget.setRowCount(0)