我想按字母顺序对QTableView中的项目进行排序。我已经搜索了互联网,但我发现只有按升序或降序排序并使用抽象模型,但在我的情况下,这些项目来自数据库。 我甚至没有明确的代码,因为我没有找到任何相关的解决方案。我只有这个代码在运行时带来错误
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)
答案 0 :(得分:1)
如果要对数据进行排序,则应覆盖模型的sort()
方法或使用订购数据的代理,在这种情况下,我将使用QSortFilterProxyModel
:
示例:
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_())