Reputation: 457
I want to sort items in a QTableView in alphabetic order. I've searched the internet but all in vein and those i find are limited to sorting in ascending or descending order and use an Abstract model yet in my case, the items are got from a database. I don't even have a clear code about it since i've not found any related solution. All i have is this code that brings an error when run
database = QtSql.QSqlDatabase().addDatabase('QSQLITE')
database.setDatabaseName('database.db')
database.open()
self.table_model1 = QtSql.QSqlQueryModel()
self.table_model1.setQuery("SELECT * FROM Individuals ")
self.tableView1.setModel(self.table_model1)
self.table_model1.setHeaderData(0, QtCore.Qt.Horizontal, "Name")
self.table_model1.setHeaderData(1, QtCore.Qt.Horizontal, "Tel No.")
self.table_model1.setHeaderData(2, QtCore.Qt.Horizontal, "Email")
self.tableView1.horizontalHeader().setVisible(True)
self.tableView1.setSortingEnabled(True)
self.tableView1.horizontalHeader().sortIndicatorChanged.connect(self.sort_table1)
def sort_table1(self):
self.tableView1.sortByColumn(0, QtCore.Qt.OrderedAlphaDither)
Upvotes: 0
Views: 1182
Reputation: 243975
If you want to sort the data you should overwrite the sort()
method of your model or use a proxy that orders the data, in this case I will use QSortFilterProxyModel
:
Example:
def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName(':memory:')
if not db.open():
print( "Cannot open database",
"Unable to establish a database connection.\n"
"This example needs SQLite support. Please read the Qt SQL "
"driver documentation for information how to build it.\n\n"
"Click Cancel to exit.")
return False
query = QtSql.QSqlQuery()
query.exec_("create table person(id int primary key, "
"firstname varchar(20), lastname varchar(20))")
query.exec_("insert into person values(101, 'Danny', 'Young')")
query.exec_("insert into person values(102, 'Christine', 'Holand')")
query.exec_("insert into person values(103, 'Lars', 'Gordon')")
query.exec_("insert into person values(104, 'Roberto', 'Robitaille')")
query.exec_("insert into person values(105, 'Maria', 'Papadopoulos')")
return True
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
if not createConnection():
sys.exit(1)
table = QtWidgets.QTableView()
table.setSortingEnabled(True)
model = QtSql.QSqlQueryModel()
model.setQuery("select * from person")
proxy = QtCore.QSortFilterProxyModel()
proxy.setSourceModel(model)
table.setModel(proxy)
table.show()
sys.exit(app.exec_())
Upvotes: 1