void MainWindow::init(){ connection=Connection::getInstance(); ui->tableView->viewport()->installEventFilter(this); model = new QSqlRelationalTableModel(0,connection->getDB()); model->setHeaderData(0, Qt::Horizontal, tr("id")); model->setHeaderData(1, Qt::Horizontal, tr("name")); model->setHeaderData(2, Qt::Horizontal, trUtf8("assort")); model->setTable("table1"); model->setRelation(2, QSqlRelation("tasrt", "id", "name_as")); model->select(); ui->tableView->setModel(model); ui->tableView->setColumnHidden(0,true); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableView->setItemDelegate(QSqlRelationalDelegate(ui->tableView)); ui->tableView->resizeColumnsToContents(); ui->tableView->resizeRowsToContents(); ui->tableView->show();}void MainWindow::saveSettings(){QItemSelectionModel *selectionModel = ui->tableView->selectionModel();QModelIndexList indexes = selectionModel->selectedRows();QModelIndex index; foreach (index, indexes) { QSqlRecord record = model->record(index.row()); QString settings_file; settings_file.append(record.value("name").toString()).append("\n"); settings_file.append(record.value("name_as").toString()).append("\n"); qDebug()<<settings_file;}}
bool mymodel::setData(const QModelIndex &index, const QVariant &value, int role ) { if (index.column() == 0 ) return false; QModelIndex primaryKeyIndex = QSqlRelationalTableModel::index(index.row(), 0); QString count_ = data(primaryKeyIndex).toString(); bool ok; switch(index.column()) { case 1: update_c = QString ("mycolumn1=' "); break; case 2: update_c = QString ("mycolumn2=' "); break; case 3:... break; } ok = setTable(count_,value.toString(),update_c); refresh(); return ok; } //-----обновление данных в таблице---- void mymodel::refresh() { QSqlQuery query1; query1.exec("select * from mytable"); setQuery(query1); } //-------------заполнение таблицы новыми данными----------- bool mymodel::setTable( const QString &count_,const QString ¶meter,const QString &update_c) { update_table = QString ("update mytable set "); update_count = QString (" ' where count=' "); QSqlQuery query2; query2.prepare(update_table+update_c+parameter+update_count+count_+"'"); query2.addBindValue(parameter); query2.addBindValue(count_); query2.exec(); return query2.exec(); }