Last active
October 17, 2017 14:57
-
-
Save micjabbour/6691cdd56c9828ee59fea7352721f119 to your computer and use it in GitHub Desktop.
QSqlQueryModel eager loading example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//based on https://doc.qt.io/qt-5/qsqlquerymodel.html#fetchMore | |
#include <QtWidgets> | |
#include <QtSql> | |
#include <type_traits> | |
//comment out the next line to disable eager loading | |
#define QSQLMODEL_EAGER_LODING 1 | |
//a class template that can be used to disable lazy loading | |
//in any QAbstractTableModel subclass | |
template<typename TableModel> | |
struct EagerlyLoaded : public TableModel { | |
static_assert(std::is_base_of<QAbstractTableModel, TableModel>::value, | |
"EagerlyLoaded works only with QAbstractTableModel subclasses"); | |
explicit EagerlyLoaded(QObject* parent = nullptr):TableModel(parent) { | |
QObject::connect(this, &QAbstractTableModel::modelReset, | |
[this]{ while(this->canFetchMore()) this->fetchMore(); }); | |
} | |
}; | |
int main(int argc, char* argv[]) { | |
QApplication a(argc, argv); | |
//setup an in-memory database table and fill it with dummy data | |
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); | |
db.setDatabaseName(":memory:"); | |
if(!db.open()) return 1; | |
QSqlQuery query; | |
query.prepare("CREATE TABLE test_table(id PRIMARY KEY, name TEXT);"); | |
if(!query.exec()) return 2; | |
query.prepare("INSERT INTO test_table(name) VALUES(?);"); | |
QVariantList values; | |
values << "aa"; // <<-- suppose that this is an interesting value to search for | |
for(int i=0; i<100000; i++) values << "bb"; //100k rows of dull values | |
values << "aa"; // another interestng value at the end | |
query.addBindValue(values); | |
if(!query.execBatch(QSqlQuery::ValuesAsRows)) return 3; | |
//setup GUI | |
QWidget w; | |
QVBoxLayout layout(&w); | |
QLineEdit lineEdit; | |
QTableView tableView; | |
layout.addWidget(&lineEdit); | |
layout.addWidget(&tableView); | |
//setup models | |
#ifdef QSQLMODEL_EAGER_LODING | |
EagerlyLoaded<QSqlQueryModel> model; | |
#else | |
QSqlQueryModel model; | |
#endif | |
QSortFilterProxyModel filterModel; | |
model.setQuery("SELECT * FROM test_table ORDER BY id;"); | |
filterModel.setSourceModel(&model); | |
filterModel.setFilterKeyColumn(1); | |
tableView.setModel(&filterModel); | |
//hookup the line edit with the filter model | |
QObject::connect(&lineEdit, &QLineEdit::textChanged, | |
&filterModel, &QSortFilterProxyModel::setFilterFixedString); | |
//set the line edit to the interesting value | |
lineEdit.setText("aa"); //this should trigger the filter model | |
w.show(); | |
return a.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment