Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- create table person (id int primary key, firstname varchar(20), lastname varchar(20), status int)
- #include <QSqlQueryModel>
- #include <QColor>
- #include <QBrush>
- #include <QSqlQuery>
- class MyModel : public QSqlQueryModel
- {
- public:
- // Константы, хранящие нужные индексы колонок
- enum { kIdColumn = 0 /* индекс колонки с id */, kStatusColumn = 3 /* индекс колонки со статусом */};
- int getStatusOfRow(int rowIndex) const {
- return data(index(rowIndex, kStatusColumn ),Qt::EditRole).toInt();
- }
- QVariant data(const QModelIndex &itemIndex, int role = Qt::DisplayRole) const override
- {
- if (role == Qt::BackgroundRole) {
- int status = getStatusOfRow(itemIndex.row());
- int row = itemIndex.row();
- if (status == 0 ) {
- return QBrush(QColor(255, 255, 0));
- }
- } else if (role == Qt::DisplayRole) {
- if (itemIndex.column() == kStatusColumn) {
- int status = getStatusOfRow(itemIndex.row());
- return status ? "Verified" : "Unverified";
- }
- }
- return QSqlQueryModel::data(itemIndex, role);
- }
- bool setStatus(int personId, int status) {
- QSqlQuery query;
- query.prepare("update person set status = ? where id = ?");
- query.addBindValue(status);
- query.addBindValue(personId);
- return query.exec();
- }
- };
- MyModel* model = new MyModel(this);
- model->setQuery("select * from person");
- model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
- model->setHeaderData(1, Qt::Horizontal, QObject::tr("First name"));
- model->setHeaderData(2, Qt::Horizontal, QObject::tr("Last name"));
- model->setHeaderData(2, Qt::Horizontal, QObject::tr("Status"));
- QTableView *view = new QTableView(parent);
- view->setModel(model);
- view->setSelectionBehavior(QAbstractItemView::SelectRows);
- void MainWindow::pushButtonClick() {
- QModelIndexList list = view->selectionModel()->selectedRows();
- if (!list.empty()) {
- int rowIndex = list.at(0).row();
- int personId = model->data(model->index(rowIndex, MyModel::kIdColumn)).toInt();
- int statusId = model->getStatusOfRow(rowIndex);
- if (statusId == 0) {
- model->setStatus(personId, 1);
- refreshModel(model);
- }
- }
- }
- void MainWindow::refreshModel(QSqlQueryModel *model) {
- model->setQuery("select * from person");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement