首页 > 解决方案 > 为什么QT QSqlTableModel不能正确排序中文?

问题描述

我用sqlite保存数据,其中一列是中文文本。我使用QSqlTableModel+QTableView。但是当我执行“Model->setSort(0, Qt::AscendingOrder)”并且第0列的数据是中文时,它没有'排序不正确。我知道这可能是编码问题,但我不知道如何修改 SQLite 的编码,

标签: c++sqliteqt

解决方案


不是编码问题。可以使用 QSortFilterProxyModel。下面是示例代码:

#include <QApplication>
#include <QSortFilterProxyModel>
#include <QTableView>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQueryModel>

int main(int argc, char* argv[]) {
  QApplication a(argc, argv);

  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
  QString dbPath = QCoreApplication::applicationDirPath() + "/test.db";
  db.setDatabaseName(dbPath);
  db.open();

  QSqlQueryModel* model = new QSqlQueryModel();
  model->setQuery("select * from test");
  QSortFilterProxyModel* sort = new QSortFilterProxyModel();
  sort->setSortLocaleAware(true);
  sort->setSourceModel(model);
  QTableView table;
  table.setModel(sort);
  table.setSortingEnabled(true);
  table.show();
  return a.exec();
}

在此处输入图像描述


推荐阅读