Reputation: 37
I am trying add basic search functionality to my project so I created a search bar and a search button, when said button is clicked I want to query a database and display the results on a table view widget.
However I still don't quite understand how to add data to the table, I tried creating a QsqlQuery and using the setQuery method of the table widget, but when I click the search button nothing happens. What am I doing wrong?
Here is my code.
def searchEvent(self):
'''
Send appropriate search query and display results on the tableView
'''
# Connect to the database
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("data.sqlite3")
db.open()
# Prepare query
query = QtSql.QSqlQuery(db)
query.prepare("SELECT * FROM SetInfo_view WHERE Name LIKE(?)")
query.bindValue(0, self.searchLineEdit.text())
# Prepare table model
tableModel = QtSql.QSqlQueryModel()
tableModel.setQuery(query)
self.tableView.setModel(tableModel)
self.tableView.show()
db.close()
Thanks in advance.
Upvotes: 0
Views: 1780
Reputation: 37
After reading the documentation I found out that it is necessary to actually execute the query before adding it as a model to the table view, like so:
def searchEvent(self):
'''
Send appropriate search query and display results on the tableView
'''
# Connect to the database
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("data.sqlite3")
db.open()
# Prepare query
query = QtSql.QSqlQuery(db)
query.prepare("SELECT * FROM SetInfo_view WHERE Name LIKE(?)")
query.bindValue(0, self.searchLineEdit.text())
query.exec_()
# Prepare table model
tableModel = QtSql.QSqlQueryModel()
tableModel.setQuery(query)
self.tableView.setModel(tableModel)
self.tableView.show()
db.close()
Source: TableView in QT5 doesn't show MYSQL Data, just empty rows are shown
Upvotes: 1