void QRelation::populateDictionary() { if (!isValid()) return; if (model == NULL) populateModel(); QSqlRecord record; QString indexColumn; QString displayColumn; for (int i=0; i < model->rowCount(); ++i) { record = model->record(i); indexColumn = rel.indexColumn(); if (m_parent->database().driver()->isIdentifierEscaped(indexColumn, QSqlDriver::FieldName)) indexColumn = m_parent->database().driver()->stripDelimiters(indexColumn, QSqlDriver::FieldName); displayColumn = rel.displayColumn(); if (m_parent->database().driver()->isIdentifierEscaped(displayColumn, QSqlDriver::FieldName)) displayColumn = m_parent->database().driver()->stripDelimiters(displayColumn, QSqlDriver::FieldName); dictionary[record.field(indexColumn).value().toString()] = record.field(displayColumn).value(); } m_dictInitialized = true; }
QSqlRelationalTableModel *EmployeeDataModel::initializeInputDataModel() { QSqlRelationalTableModel *model = new QSqlRelationalTableModel(this, this->db); model->setTable(QLatin1String("employee")); return model; }
void ui_module_articulos::on_pushButton_eliminar_2_clicked() { QModelIndexList list = ui->tableView_articulos->selectionModel()->selectedRows(); int filas = list.size(); if(filas==0) { QMessageBox::information(this,"Error","Por favor, seleccione una fila para eliminar"); } else { int rpta = QMessageBox::question(this,"Confirmación","Esta seguro de eliminar "+QString::number(filas)+" articulos?","Aceptar","Cancelar"); if(rpta==0) { bool ok = true; for(int i=0;i<filas;i++) { QSqlRelationalTableModel * model = (QSqlRelationalTableModel*)ui->tableView_articulos->model(); QSqlRecord record = model->record(list.at(i).row()); object_e_articulo obj; obj.mf_load(record.value(COD).toString()); obj.mf_set_habilitado(C_NO_HABILITADO); //Si ocurre un error if (!obj.mf_update()) { ok = false; } } if(!ok) { //Mostramos mensaje de error QMessageBox::information(this,"Error",C_ERROR_ELIMINAR_ARTICULO) ; } else { //No ocurre ningun error update_table_articulos(); } } } }
QSqlRelationalTableModel* EkonTables::createRelationalTableModel(QWidget *parentWidget, QString tableName, QStringList columnNames, QList<QPair<int, QSqlRelation> > relations) { QSqlRelationalTableModel *tableModel = new QSqlRelationalTableModel(parentWidget, DbService::getInstance()->getCurrentDatabase()); tableModel->setTable(tableName); for (auto relation : relations) tableModel->setRelation(relation.first, relation.second); configureTableModel(tableModel, columnNames); return tableModel; }
void ui_module_articulos::update_table_articulos() { //Limipiamos el model anterior QAbstractItemModel * anteriorModel = ui->tableView_articulos->model(); if(anteriorModel) delete anteriorModel; //Creamos el nuevo model QSqlRelationalTableModel * model = new QSqlRelationalTableModel(); model->setTable(v_articuloProveedor); /* model->setRelation(GRUPO,QSqlRelation(e_grupo,pk_grupo,descripcion)); model->setRelation(MARCA,QSqlRelation(e_marca,pk_marca,descripcion)); model->setRelation(MEDIDA,QSqlRelation(e_medida,pk_medida,descripcion)); model->setJoinMode(QSqlRelationalTableModel::LeftJoin); model->setFilter("habilitado=1");*/ for(int i=0;i<num_header;i++) { model->setHeaderData(i,Qt::Horizontal,tableHeaders[i]); } if(model->select()) { ui->tableView_articulos->setModel(model); ui->busqueda->setTableModel(model); } else { qDebug()<<model->query().lastError(); qDebug()<<model->query().lastQuery(); QMessageBox::information(this,"Error","Ocurrio un error al cargar la información"); } //Ocultamos columnas ui->tableView_articulos->setColumnHidden(GRUPO,true); ui->tableView_articulos->setColumnHidden(HABILITADO,true); ui->tableView_articulos->horizontalHeader()->setResizeMode(QHeaderView::Stretch); //qDebug()<<model->query().lastQuery()<<endl; }
void ui_module_articulos::on_pushButton_editar_2_clicked() { QModelIndexList list = ui->tableView_articulos->selectionModel()->selectedRows(); int filas = list.size(); if(filas>1) { QMessageBox::information(this,"Error","Solo se puede editar una fila a la vez"); } else { if(filas==0) { QMessageBox::information(this,"Error","Por favor, seleccione una fila para editar"); } else { object_e_articulo articulo; QSqlRelationalTableModel * model = (QSqlRelationalTableModel*)ui->tableView_articulos->model(); QSqlRecord record = model->record(list.at(0).row()); articulo.mf_set_pk_articulo(record.value(COD).toString()); articulo.mf_set_descripcion(record.value(DESCRIPCION).toString()); articulo.mf_set_fk_marca(record.value(MARCA).toString()); articulo.mf_set_fk_grupo(record.value(GRUPO).toString()); articulo.mf_set_fk_medida(record.value(MEDIDA).toString()); articulo.mf_set_precio_lista(record.value(PRECIO).toString()); articulo.mf_set_stock(record.value(STOCK).toString()); ui_edit_articulo form_edit_articulos(&articulo) ; form_edit_articulos.exec(); //Actualizamos la tabla de articulos update_table_articulos(); } } }
void MainWindow::addOrEditTreeItem(DialogMode mode, TreeItem treeItem, const QModelIndex &index) { const int eventsTableRow = rootModelIndex(index).row(); int eventsTableColumn = -1; int itemTableNameColumn = -1; QSqlRelationalTableModel *tableModel = 0; SqlRelationalTableDialog *tableDialog = 0; switch (treeItem) { case CharacterItem: eventsTableColumn = 2; itemTableNameColumn = 1; tableModel = database->characters(); tableDialog = new CharacterDialog(tableModel, this); break; case ConversationItem: eventsTableColumn = 3; itemTableNameColumn = 3; tableModel = database->conversations(); tableDialog = new ConversationDialog(tableModel, this); break; } QModelIndex eventsIndex = database->events()->index(eventsTableRow, eventsTableColumn); const QString &conversation = eventsIndex.data().toString(); QModelIndex firstItem = tableModel->index(0, itemTableNameColumn); QModelIndexList itemIndexes = tableModel->match(firstItem, Qt::DisplayRole, conversation); //Q_ASSERT(!itemIndexes.isEmpty()); //if (itemIndexes.isEmpty()) // return; QModelIndex itemIndex; if (!itemIndexes.isEmpty()) itemIndex = itemIndexes.first(); editViewItem(itemIndex, tableDialog, mode); }
void QRelation::populateModel() { if (!isValid()) return; Q_ASSERT(m_parent != NULL); if (!model) { model = new QSqlTableModel(m_parent, m_parent->database()); model->setTable(rel.tableName()); model->select(); } }
void MySqlRelationDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (!index.isValid()) return; QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel *>(model); QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0; QComboBox *combo = qobject_cast<QComboBox *>(editor); if (!sqlModel || !childModel || !combo) { if (HandbookDialog::m_record.fieldName(index.column()).contains("IS_", Qt::CaseSensitive)) { QCheckBox * checkBox = qobject_cast<QCheckBox *>(editor); sqlModel->setData(index, checkBox->isChecked(), Qt::DisplayRole); sqlModel->setData(index, checkBox->isChecked(), Qt::EditRole); return; } else if (HandbookDialog::m_record.fieldName(index.column()).contains("DATE_", Qt::CaseSensitive)) { QDateEdit * dateEdit = qobject_cast<QDateEdit *>(editor); sqlModel->setData(index, dateEdit->date().toString("yyyy-MM-dd"), Qt::DisplayRole); sqlModel->setData(index, dateEdit->date().toString("yyyy-MM-dd"), Qt::EditRole); return; } else { QItemDelegate::setModelData(editor, model, index); return; } } int currentItem = combo->currentIndex(); int childColIndex = childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn()); int childEditIndex = childModel->fieldIndex(sqlModel->relation(index.column()).indexColumn()); sqlModel->setData(index, childModel->data(childModel->index(currentItem, childColIndex), Qt::DisplayRole), Qt::DisplayRole); sqlModel->setData(index, childModel->data(childModel->index(currentItem, childEditIndex), Qt::EditRole), Qt::EditRole); }
void mySqlRelationalDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (!index.isValid()) return; QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel *>(model); QSortFilterProxyModel* proxyModel = NULL; if (!sqlModel ) { proxyModel = qobject_cast<QSortFilterProxyModel *>(model); if (proxyModel) sqlModel = qobject_cast<QSqlRelationalTableModel *>(proxyModel->sourceModel()); } QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0; QComboBox *combo = qobject_cast<QComboBox *>(editor); if (!sqlModel || !childModel || !combo) { QItemDelegate::setModelData(editor, model, index); return; } int currentItem = combo->currentIndex(); int childColIndex = childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn()); int childEditIndex = childModel->fieldIndex(sqlModel->relation(index.column()).indexColumn()); if (proxyModel) { proxyModel->setData(index, childModel->data(childModel->index(currentItem, childColIndex), Qt::DisplayRole), Qt::DisplayRole); proxyModel->setData(index, childModel->data(childModel->index(currentItem, childEditIndex), Qt::EditRole), Qt::EditRole); } else { sqlModel->setData(index, childModel->data(childModel->index(currentItem, childColIndex), Qt::DisplayRole), Qt::DisplayRole); sqlModel->setData(index, childModel->data(childModel->index(currentItem, childEditIndex), Qt::EditRole), Qt::EditRole); } }
void MainWindow::editViewItem(const QModelIndex &index, SqlRelationalTableDialog *dialog, DialogMode mode) { int row = 0; const QModelIndex &rootIndex = rootModelIndex(index); //Q_ASSERT(rootIndex.isValid()); if (rootIndex.isValid()) row = rootIndex.row(); Q_ASSERT(dialog); if (!dialog) return; QSqlRelationalTableModel *model = dialog->model(); Q_ASSERT(model); if (!model) return; if (mode == NewMode) { bool rowWasInserted = model->insertRow(row); Q_ASSERT(rowWasInserted); if (!rowWasInserted) return; } dialog->setRow(row); int result = dialog->exec(); if (mode == NewMode && result == QDialog::Rejected) { bool rowWasRemoved = model->removeRow(row); Q_UNUSED(rowWasRemoved); Q_ASSERT(rowWasRemoved); } delete dialog; //reloadEvents(); }
TaskCheckBox::TaskCheckBox(SideBarTask* sidebar, int row, QWidget *parent) : QWidget(parent), ui(new Ui::taskWidget), sidebar(sidebar) { this->row = row; ui->setupUi(this); setStyleSheet(TaskCheckBox::defaultCSS); removeTaskBtn = new QPushButton("X"); checkbox = new QCheckBox(); taskName = new QLabel; termDate = new TermDate; priority = new Priority; ui->taskLayout->addWidget(checkbox,1); ui->taskLayout->addWidget(priority, 0, Qt::AlignLeft); ui->taskLayout->addWidget(taskName,10); ui->taskLayout->addWidget(new QLabel("")); ui->taskLayout->addWidget(termDate, 0, Qt::AlignLeft); ui->taskLayout->addWidget(removeTaskBtn, 0, Qt::AlignLeft); QSqlRelationalTableModel* model = Task::getInstance()->getModel(); mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setModel(model); mapper->addMapping(taskName, model->fieldIndex("name"), "text"); mapper->addMapping(termDate, model->fieldIndex("termDate")); mapper->addMapping(checkbox, model->fieldIndex("isFinished")); mapper->addMapping(priority, model->fieldIndex("priority")); // priority->setText(QString::number(row)); // DEBUG mapper->setCurrentIndex(row); connect(checkbox, SIGNAL(stateChanged(int)), mapper, SLOT(submit())); connect(this,SIGNAL(editTask(int)), sidebar, SLOT(loadTask(int))); connect(removeTaskBtn, SIGNAL(clicked()), this, SLOT(onRemoveTaskClicked())); }
SQLOpenProjectDialog::SQLOpenProjectDialog(const QString & host, unsigned int port, const QString & dbname, const QString & user, const QString & password,QWidget *parent) : QDialog(parent), ui(new Ui::SQLOpenProjectDialog) { ui->setupUi(this); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); m_Host=host; m_Port=port; m_DBName=dbname; m_User=user; m_Password=password; db.setHostName(m_Host); db.setPort(m_Port); db.setDatabaseName(m_DBName); db.setUserName(m_User); db.setPassword(m_Password); bool ok=db.open(); std::cout << db.lastError().databaseText().toStdString() << std::endl; if(ok){ QSqlRelationalTableModel *model = new QSqlRelationalTableModel(this,db); model->setTable("Project"); model->setEditStrategy(QSqlTableModel::OnRowChange); model->select(); ui->existingProjectsTableView->setModel(model); }else{ } m_Accepted=false; m_Project=0; }
Widget::Widget(QWidget *parent) : QWidget(parent) { resize(400,300); if(connect()) { QTableView *view = new QTableView(this); QSqlRelationalTableModel *model = new QSqlRelationalTableModel;//要先有数据才能创建model,也就是先连接数据库局 view->setGeometry(0,0,400,300); view->setModel(model); model->setTable("student"); model->setSort(0,Qt::AscendingOrder); // model->setHeaderData(0,Qt::Horizontal,"Name");//from 0 // model->setHeaderData(1,Qt::Horizontal,"Age"); // model->setHeaderData(2,Qt::Horizontal,"likes"); model->setRelation(3,QSqlRelation("city","id","name")); model->select(); // view->setModel(model); view->setSelectionMode(QAbstractItemView::SingleSelection);//设置选择模式 view->setSelectionBehavior(QAbstractItemView::SelectRows);//选择行 // view->resizeColumnsToContents();//tiaozhengziti view->setEditTriggers(QAbstractItemView::DoubleClicked);//不可编辑? QHeaderView *header = view->horizontalHeader(); header->setStretchLastSection(true); view->setItemDelegate(new QSqlRelationalDelegate(view)); // QHeaderView *head = view->verticalHeader(); // head->setStretchLastSection(true); // view->show(); // this?->show(); } }
void BadgeWindow::timer() { DialogTimer dialogTimer; bool saveRequest; QString taskName; QTime elapsedTime; saveRequest = dialogTimer.getTaskInfo(taskName, elapsedTime); if (saveRequest) { DialogTask dialog; QSqlRelationalTableModel *taskModel; taskModel = new QSqlRelationalTableModel(); taskModel->setEditStrategy(QSqlTableModel::OnManualSubmit); taskModel->setTable("task"); qDebug() << "Day" << QDate::currentDate().toString("yyyy-MM-dd") << endl; taskModel->setFilter("day='" + QDate::currentDate().toString("yyyy-MM-dd") + "'"); //taskModel.setEditStrategy(QSqlTableModel::OnFieldChange); taskModel->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); taskModel->setHeaderData(1, Qt::Horizontal, QObject::tr("Date")); taskModel->setHeaderData(2, Qt::Horizontal, QObject::tr("Elapsed")); //taskModel->setHeaderData(3, Qt::Horizontal, QObject::tr("Attivita'")); taskModel->setRelation(3, QSqlRelation("attivita", "id", "attivita")); taskModel->select(); // TODO: if current date don't exist create it dialog.openTask("Task", "Elapsed", taskModel, QDate::currentDate(), "task", elapsedTime, taskName); delete taskModel; } }
QSqlTableModel *EmployeeDataModel::initializeViewModel() { //TODO: id als locale Konstante QSqlRelationalTableModel *model = new QSqlRelationalTableModel(this); model->setTable(QLatin1String("employee_view")); model->setEditStrategy(QSqlTableModel::OnFieldChange); model->setHeaderData(POS_EMPLOYEE_FIRSTNAME, Qt::Horizontal, QObject::tr("Firstname")); model->setHeaderData(POS_EMPLOYEE_LASTNAME, Qt::Horizontal, QObject::tr("Lastname")); model->select(); return model; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); if(!createConnection(db)) return 1; /* QSqlQueryModel * mode = new QSqlQueryModel; mode->setQuery("select prod_id, vend_name, prod_name, prod_price from products, vendors where products.vend_id = vendors.vend_id", db); mode->setHeaderData(0, Qt::Horizontal, "prod_id"); mode->setHeaderData(1, Qt::Horizontal, "vend_name"); mode->setHeaderData(2, Qt::Horizontal, "prod_name"); mode->setHeaderData(3, Qt::Horizontal, "prod_price"); */ QSqlRelationalTableModel * mode = new QSqlRelationalTableModel; mode->setTable("products"); QSqlRelation relation("vendors", "vend_id", "vend_name"); mode->setRelation(1, relation); mode->select(); mode->setHeaderData(0, Qt::Horizontal, "prod_id"); mode->setHeaderData(1, Qt::Horizontal, "vend_name"); mode->setHeaderData(2, Qt::Horizontal, "prod_name"); mode->setHeaderData(3, Qt::Horizontal, "prod_price"); QTableView * tableview = new QTableView(&w); tableview->verticalHeader()->hide(); tableview->setModel(mode); w.setCentralWidget(tableview); w.resize(600, 400); w.show(); return a.exec(); }
void CarsEdit::FillTable() { QString str_oper = "SELECT hm_cars.id, hm_cars.name, hm_cars.speed, hm_fuel.name, hm_fuel.id FROM hm_cars INNER JOIN hm_fuel ON hm_cars.fuel_id = hm_fuel.id;"; QSqlQueryModel * model_Oper = new QSqlQueryModel(0); model_Oper->setQuery(str_oper); model_Oper->setHeaderData(1, Qt::Horizontal, QObject::trUtf8("Название автомобиля")); model_Oper->setHeaderData(2, Qt::Horizontal, QObject::trUtf8("Максимальная скорость")); model_Oper->setHeaderData(3, Qt::Horizontal, QObject::trUtf8("Тип топлива")); ui->tableView->setModel(model_Oper); ui->tableView->hideColumn(0); ui->tableView->hideColumn(4); QSqlRelationalTableModel *comboModel = new QSqlRelationalTableModel(0); comboModel->setTable("hm_fuel"); int comboIndex = comboModel->fieldIndex("id"); comboModel->setRelation(comboIndex, QSqlRelation("hm_fuel", "id", "name")); comboModel->select(); QSqlTableModel *comboRelModel = comboModel->relationModel(comboIndex); ui->comboBox->setModel(comboRelModel); ui->comboBox->setModelColumn(comboRelModel->fieldIndex("name")); }
/* ** public: */ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , m_timer(new QBasicTimer) , m_dataProvider(new DataProvider(this)) , m_dialogSettings(0) // Guarded by QPointer , m_dialogAbout(0) // Guarded by QPointer { qDebug() << Q_FUNC_INFO; /* m_dataModel = new QStandardItemModel(this); m_dataModel->setColumnCount(5); */ setupUi(this); /* QStringList labels; labels << tr("Show name") << tr("Episode name") << tr("Season #") << tr("Episode #") << tr("Date"); m_dataModel->setHorizontalHeaderLabels(labels); // showsTableView->setModel(m_dataModel); showsTableView->setModel(DbInterface::instance().readEpisodes()); showsTableView->verticalHeader()->hide(); showsTableView->horizontalHeader()->setResizeMode(QHeaderView::Interactive); showsTableView->horizontalHeader()->setStretchLastSection(true); showsTableView->horizontalHeader()->setCascadingSectionResizes(true); showsTableView->horizontalHeader()->setHighlightSections(true); showsTableView->horizontalHeader()->setMovable(true); srand(QTime::currentTime().toString("hhmmsszzz").toUInt()); // Fill with random stuff for (int i=0; i<30; ++i) { m_dataModel->setItem(i, 0, new QStandardItem(QString("show_%1").arg(i))); m_dataModel->setItem(i, 1, new QStandardItem(QString("episode_%1").arg(i))); m_dataModel->setItem(i, 2, new QStandardItem(QString("%1").arg(rand()%10+1))); m_dataModel->setItem(i, 3, new QStandardItem(QString("%1").arg(rand()%24+1))); QDate rndDate = QDate::currentDate().addDays(i); m_dataModel->setItem(i, 4, new QStandardItem(rndDate.toString("yyyy/MM/dd"))); } */ setWindowTitle(QString("nextShows - v%1").arg(NEXTSHOWS_VERSION)); statusBar()->showMessage(tr("nextShows started"), 1000*3); // TEMPORARY CODE FOR TESTING //////////////////////////////////////////// QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "NS_View"); db.setDatabaseName("ns.db"); db.open(); QSqlRelationalTableModel *model = new QSqlRelationalTableModel(this, db); model->setTable("T_Episodes"); model->setRelation(model->fieldIndex("shows_id"), QSqlRelation("T_Shows", "idT_Shows", "ShowName")); model->setSort(model->fieldIndex("Date"), Qt::AscendingOrder); model->select(); QStringList hideFields; hideFields << "idT_Episodes" << "ProdNumber" << "EpisodeCount" << "EpisodeUrl" << "isSpecial"; foreach (QString field, hideFields) { model->removeColumn(model->fieldIndex(field)); }
QSqlRelationalTableModel * AddStoragePlace::getBoxModel(QString tableName) { QSqlRelationalTableModel *m = new QSqlRelationalTableModel(); m->setTable(tableName); m->select(); return m; }
void UserForm:: createTableModels() { QSqlRelationalTableModel* model = new QSqlRelationalTableModel(); model->setTable("good"); model->setRelation(Producer, QSqlRelation("company", "companyid", "name")); model->setRelation(Catalog, QSqlRelation("catalog", "id", "name")); model->setHeaderData(Producer, Qt::Horizontal, "Producer"); model->setHeaderData(Name, Qt::Horizontal, "Name"); model->setHeaderData(Price, Qt::Horizontal, "Price, $"); model->setHeaderData(Description, Qt::Horizontal, "Description"); model->setHeaderData(Catalog, Qt::Horizontal, "Catalog"); model->setFilter("catalog_id IS NOT NULL"); // model->removeColumn(5); model->select(); productsModel = model; model = new QSqlRelationalTableModel(); model->setTable("`order`"); model->setRelation(goodId, QSqlRelation("good", "goodid", "name")); model->setFilter("user_login='******'"); model->select(); model->setEditStrategy(QSqlTableModel::OnRowChange); model->removeColumn(3); model->removeColumn(2); model->setHeaderData(orderId, Qt::Horizontal, "Order #"); model->setHeaderData(goodId, Qt::Horizontal, "Product"); model->setHeaderData(date, Qt::Horizontal, "Date"); model->setHeaderData(address, Qt::Horizontal, "Address to deliver"); ordersModel = model; }
SideBarTask::SideBarTask(QWidget *parent) : QWidget(parent), ui(new Ui::sideBarTask) { ui->setupUi(this); layout = new QVBoxLayout(); // task course courseDropDown = new QComboBox(); // task type taskType = new TriStateButton("Type: ", "TE","Devoir", "Labo"); // Task name taskName = new QLineEdit(); taskName->setPlaceholderText("Titre de la tache"); // Task description description = new QTextEdit(); description->setPlaceholderText("Description"); description->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding); description->setMinimumHeight(20); description->setMaximumHeight(100); // task priority priority = new TriStateButton("Priorité: ", "Basse", "Moyenne", "Haute"); // task term termDate = new QDateTimeEdit; termDate->setCalendarPopup(true); hasTerm = new QCheckBox("Echéance"); hasTerm->setChecked(false); connect(hasTerm, SIGNAL(clicked(bool)), termDate, SLOT(setEnabled(bool)) ); termDate->setEnabled(false); // Task Submit btnSubmit = new QPushButton(); btnSubmit->setText("Sauver"); btnSubmit->setDefault(false); btnSubmit->setAutoDefault(true); QSqlRelationalTableModel *model = Task::getInstance()->getModel(); courseIndex = Task::getInstance()->getCourseIndex(); //SQLRelation set dropdown to search course name in DB relModel = model->relationModel(courseIndex); courseDropDown->setModel(relModel); courseDropDown->setModelColumn(relModel->fieldIndex("name")); mapper = new QDataWidgetMapper(this); mapper->setModel(model); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setItemDelegate(new QSqlRelationalDelegate(this)); // Mapping mapper->addMapping(taskName, model->fieldIndex("name")); mapper->addMapping(description, model->fieldIndex("description")); mapper->addMapping(courseDropDown, courseIndex); mapper->addMapping(priority, model->fieldIndex("priority")); mapper->addMapping(taskType, model->fieldIndex("typeId")); mapper->addMapping(termDate, model->fieldIndex("termDate")); // Ajout des widgets au layout layout->addWidget(courseDropDown); layout->addWidget(taskType); layout->addSpacing(10); layout->addWidget(taskName); layout->addWidget(description); layout->addSpacing(10); layout->addWidget(hasTerm); layout->addWidget(termDate); layout->addSpacing(10); layout->addWidget(priority); layout->addWidget(btnSubmit, QDialogButtonBox::AcceptRole); layout->addStretch(); connect(btnSubmit, SIGNAL(clicked()), this , SLOT(submitTask())); mapper->toFirst(); this->setLayout(layout); }
QSqlRelationalTableModel *EmployeeDataModel::initializeRelationalModel() { //TODO: id als locale Konstante QSqlRelationalTableModel *model = new QSqlRelationalTableModel(this); model->setTable(QLatin1String("employee")); model->setEditStrategy(QSqlTableModel::OnFieldChange); model->setRelation(POS_EMPLOYEE_TITLE_ID, QSqlRelation(QLatin1String("title"), QLatin1String("title_id"), QLatin1String("name"))); model->setRelation(POS_EMPLOYEE_ADDRESS_ID, QSqlRelation(QLatin1String("address"), QLatin1String("address_id"), QLatin1String("address"))); model->setRelation(POS_EMPLOYEE_DEPARTMENT_ID, QSqlRelation(QLatin1String("department"), QLatin1String("department_id"), QLatin1String("name"))); model->setRelation(POS_EMPLOYEE_FUNCTION_ID, QSqlRelation(QLatin1String("function"), QLatin1String("function_id"), QLatin1String("name"))); model->setRelation(POS_EMPLOYEE_COMPUTER_ID, QSqlRelation(QLatin1String("computer"), QLatin1String("computer_id"), QLatin1String("network_name"))); model->setRelation(POS_EMPLOYEE_PRINTER_ID, QSqlRelation(QLatin1String("printer"), QLatin1String("printer_id"), QLatin1String("network_name"))); model->setRelation(POS_EMPLOYEE_PHONE_ID, QSqlRelation(QLatin1String("phone"), QLatin1String("phone_id"), QLatin1String("number"))); model->setRelation(POS_EMPLOYEE_MOBILE_ID, QSqlRelation(QLatin1String("mobile"), QLatin1String("mobile_id"), QLatin1String("number"))); model->setRelation(POS_EMPLOYEE_FAX_ID, QSqlRelation(QLatin1String("fax"), QLatin1String("fax_id"), QLatin1String("number"))); model->setHeaderData(POS_EMPLOYEE_ID, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(POS_EMPLOYEE_NR, Qt::Horizontal, QObject::tr("Emp.Number")); model->setHeaderData(POS_EMPLOYEE_GENDER, Qt::Horizontal, QObject::tr("Gender")); model->setHeaderData(POS_EMPLOYEE_TITLE_ID, Qt::Horizontal, QObject::tr("Title")); model->setHeaderData(POS_EMPLOYEE_FIRSTNAME, Qt::Horizontal, QObject::tr("Firstname")); model->setHeaderData(POS_EMPLOYEE_LASTNAME, Qt::Horizontal, QObject::tr("Lastname")); model->setHeaderData(POS_EMPLOYEE_ADDRESS_ID, Qt::Horizontal, QObject::tr("address")); model->setHeaderData(POS_EMPLOYEE_BIRTHDAY, Qt::Horizontal, QObject::tr("Birthday")); model->setHeaderData(POS_EMPLOYEE_EMAIL, Qt::Horizontal, QObject::tr("EMail")); model->setHeaderData(POS_EMPLOYEE_DATACARE, Qt::Horizontal, QObject::tr("Datacare")); model->setHeaderData(POS_EMPLOYEE_ACTIVE, Qt::Horizontal, QObject::tr("Active")); model->setHeaderData(POS_EMPLOYEE_STARTDATE, Qt::Horizontal, QObject::tr("StartDate")); model->setHeaderData(POS_EMPLOYEE_ENDDATE, Qt::Horizontal, QObject::tr("EndDate")); model->setHeaderData(POS_EMPLOYEE_DEPARTMENT_ID, Qt::Horizontal, QObject::tr("Department")); model->setHeaderData(POS_EMPLOYEE_FUNCTION_ID, Qt::Horizontal, QObject::tr("Function")); model->setHeaderData(POS_EMPLOYEE_COMPUTER_ID, Qt::Horizontal, QObject::tr("Computer")); model->setHeaderData(POS_EMPLOYEE_PRINTER_ID, Qt::Horizontal, QObject::tr("Printer")); model->setHeaderData(POS_EMPLOYEE_PHONE_ID, Qt::Horizontal, QObject::tr("Phone")); model->setHeaderData(POS_EMPLOYEE_MOBILE_ID, Qt::Horizontal, QObject::tr("Mobile")); model->setHeaderData(POS_EMPLOYEE_FAX_ID, Qt::Horizontal, QObject::tr("Fax")); model->setHeaderData(POS_EMPLOYEE_EMPLOYEE_ACCOUNT_ID, Qt::Horizontal, QObject::tr("Accounts")); model->setHeaderData(POS_EMPLOYEE_EMPLOYEE_DOCUMENT_ID, Qt::Horizontal, QObject::tr("Documents")); model->setHeaderData(POS_EMPLOYEE_LAST_UPDATE, Qt::Horizontal, QObject::tr("Last Update")); model->select(); return model; }
HandbookDialog::HandbookDialog(QString tableName, QString tableRusName, const QSqlDatabase &database, QWidget *parent, QStringList hiddenColumns): m_database(database), mHiddenColumns(hiddenColumns), QDialog(parent), ui(new Ui::HandbookDialog) { ui->setupUi(this); ui->label->setText(tableRusName); this->setWindowTitle("Редактирование справочника: " + tableRusName); QMap<QString, QString> rusFieldNames = DataBaseExpert::fieldTranslationMap(m_database); auto ralTablesForFields = DataBaseExpert::ralationTablesForFields(m_database); m_record = database.record(tableName); QSqlRelationalTableModel * model = new QSqlRelationalTableModel(0, database); model->setTable(tableName); for (int i = 0; i < m_record.count(); ++i) { QString fieldName = m_record.fieldName(i); if (fieldName.size() > 3 && fieldName.right(3) == "_FK") { model->setRelation(i, QSqlRelation(ralTablesForFields[fieldName], "UID", "NAME")); } } model->setEditStrategy(QSqlTableModel::OnManualSubmit); //model->removeColumn(0); model->select(); for (int i = 0; i < m_record.count(); ++i) { model->setHeaderData(i, Qt::Horizontal, rusFieldNames[m_record.fieldName(i)]); if (mHiddenColumns.contains(m_record.fieldName(i), Qt::CaseInsensitive)) { ui->tableView->setColumnHidden(i, true); } } ui->tableView->setModel(model); ui->tableView->setItemDelegate(new MySqlRelationDelegate(ui->tableView)); for (int i = 0; i < m_record.count(); ++i) { if (mHiddenColumns.contains(m_record.fieldName(i), Qt::CaseInsensitive)) { ui->tableView->setColumnHidden(i, true); } } connect(ui->btnInsert, &QPushButton::clicked, [model]() { model->insertRow(model->rowCount()); }); connect(ui->btnSave, &QPushButton::clicked, [model]() { if (!model->submitAll()) qDebug() << model->lastError().text(); }); connect(ui->btnRevert, &QPushButton::clicked, [model]() { model->revertAll(); }); connect(ui->btnExit, &QPushButton::clicked, [this]() { this->accept(); }); ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::Stretch); connect(ui->tableView, &QTableView::customContextMenuRequested, [this, &tableName, model] (const QPoint& pos) { QMenu * contextMenu = new QMenu(tr("Выбор действия со строкой"), ui->tableView); QAction* insertAction = new QAction(tr("Добавить"), contextMenu); contextMenu->addAction(insertAction); connect(insertAction, &QAction::triggered, [this, &model] () { model->insertRow(model->rowCount()); }); QAction * delAction = new QAction(tr("Удалить"), contextMenu); contextMenu->addAction(delAction); connect(delAction, &QAction::triggered, [this, &pos, &tableName, model] () { QPoint transformPos = pos; transformPos.setX(20); QModelIndex index = ui->tableView->indexAt(transformPos); QString recordId = ui->tableView->model()->data(index).toString(); QSqlQuery query("DELETE FROM " + tableName + " WHERE UID = " + recordId, m_database); query,exec(); model->submitAll(); }); contextMenu->exec(ui->tableView->viewport()->mapToGlobal(pos)); }); // connect(ui->label_2, &QLabel::linkActivated, [this]() // { // WebReportDialog dlg(this->ui->label_2->text(), this); // dlg.exec(); // }); }
void Carga::loadCargas(QDate start, QDate end){ QSqlRelationalTableModel *model = new QSqlRelationalTableModel(0, QSqlDatabase::database()); model->setTable("cargas"); model->setRelation(2, QSqlRelation("cereales", "id", "cereal")); model->setRelation(15, QSqlRelation("transportista", "cuit", "nombre")); model->setRelation(8, QSqlRelation("cliente", "cuit", "nombre")); model->setRelation(5, QSqlRelation("localizacion", "id", "lugar")); model->setRelation(7, QSqlRelation("tipo_operacion", "id", "name")); model->setRelation(11, QSqlRelation("boolean", "id", "name")); model->setRelation(12, QSqlRelation("boolean", "id", "name")); model->setRelation(13, QSqlRelation("boolean", "id", "name")); model->setRelation(14, QSqlRelation("boolean", "id", "name")); model->setRelation(19, QSqlRelation("boolean", "id", "name")); QString filter = "fecha BETWEEN '" + start.toString("yyyy-MM-dd") + "' AND '" + end.toString("yyyy-MM-dd") + "'"; model->setFilter(filter); model->setHeaderData(1, Qt::Horizontal, QObject::tr("Fecha")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Grano")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("Cosecha")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("Kilos")); model->setHeaderData(5, Qt::Horizontal, QObject::tr("Origen")); model->setHeaderData(6, Qt::Horizontal, QObject::tr("N° C porte")); model->setHeaderData(7, Qt::Horizontal, QObject::tr("Tipo")); model->setHeaderData(8, Qt::Horizontal, QObject::tr("Cliente")); model->setHeaderData(9, Qt::Horizontal, QObject::tr("Tarifa a cobrar")); model->setHeaderData(10, Qt::Horizontal, QObject::tr("Tarifa a pagar")); model->setHeaderData(11, Qt::Horizontal, QObject::tr("Se cobra")); model->setHeaderData(12, Qt::Horizontal, QObject::tr("Se paga")); model->setHeaderData(13, Qt::Horizontal, QObject::tr("Pagado")); model->setHeaderData(14, Qt::Horizontal, QObject::tr("Cobrado")); model->setHeaderData(15, Qt::Horizontal, QObject::tr("Transportista")); model->setHeaderData(16, Qt::Horizontal, QObject::tr("Observaciones")); model->setHeaderData(17, Qt::Horizontal, QObject::tr("Origen")); model->setHeaderData(18, Qt::Horizontal, QObject::tr("Destino")); model->setHeaderData(19, Qt::Horizontal, QObject::tr("En depósito")); model->select(); ui->cargas->setModel(model); ui->cargas->setItemDelegate(new QSqlRelationalDelegate(ui->cargas)); ui->cargas->setSortingEnabled(true); ui->cargas->setVisible(false); ui->cargas->resizeColumnsToContents(); ui->cargas->setVisible(true); // OCULTAR COLUMNAS CARGAS ui->cargas->setColumnHidden(0,true); ui->pushButton_3->setDisabled(true); }
void XTreeView::setRelations() { if (DEBUG) qDebug("setRelations() entered with table %s.%s", qPrintable(_schemaName), qPrintable(_tableName)); QSqlRelationalTableModel *model = qobject_cast<QSqlRelationalTableModel*>(&_model); if (! model) return; // _fkeymap is for cases where there's strict adherence to naming conventions: // othertable[_qualifier]_basetable_id -> basetable_id // special cases are handled individually below // TODO: make _fkeymap static so it can be shared if (_fkeymap.size() == 0) { _fkeymap.insert("acalitem", "acalitem_name"); _fkeymap.insert("accnt", "accnt_number"); _fkeymap.insert("addr", "addr_number"); _fkeymap.insert("alarm", "alarm_number"); _fkeymap.insert("bankaccnt", "bankaccnt_name"); _fkeymap.insert("bankadjtype", "bankadjtype_name"); _fkeymap.insert("budghead", "budghead_name"); _fkeymap.insert("calhead", "calhead_name"); _fkeymap.insert("carrier", "carrier_name"); _fkeymap.insert("char", "char_name"); _fkeymap.insert("checkhead", "checkhead_number"); _fkeymap.insert("classcode", "classcode_code"); _fkeymap.insert("cmd", "cmd_title"); _fkeymap.insert("cmdarg", "cmdarg_arg"); _fkeymap.insert("cmhead", "cmhead_number"); _fkeymap.insert("cmnttype", "cmnttype_name"); _fkeymap.insert("cntct", "cntct_number"); _fkeymap.insert("cntslip", "cntslip_number"); _fkeymap.insert("cohead", "cohead_number"); _fkeymap.insert("company", "company_number"); _fkeymap.insert("costcat", "costcat_code"); _fkeymap.insert("costelem", "costelem_type"); _fkeymap.insert("country", "country_abbr"); _fkeymap.insert("crmacct", "crmacct_number"); _fkeymap.insert("curr", "curr_symbol"); _fkeymap.insert("curr_symbol", "curr_abbr"); _fkeymap.insert("custgrp", "custgrp_name"); _fkeymap.insert("custinfo", "cust_number"); _fkeymap.insert("custtype", "custtype_code"); _fkeymap.insert("dept", "dept_number"); _fkeymap.insert("destination", "destination_name"); _fkeymap.insert("ediform", "ediform_file"); _fkeymap.insert("ediprofile", "ediprofile_name"); _fkeymap.insert("emp", "emp_code"); _fkeymap.insert("empgrp", "empgrp_name"); _fkeymap.insert("evnttype", "evnttype_name"); _fkeymap.insert("expcat", "expcat_code"); _fkeymap.insert("flhead", "flhead_name"); _fkeymap.insert("form", "form_name"); _fkeymap.insert("freightclass","freightclass_code"); _fkeymap.insert("grp", "grp_name"); _fkeymap.insert("hnfc", "hnfc_code"); _fkeymap.insert("image", "image_name"); _fkeymap.insert("incdt", "incdt_number"); _fkeymap.insert("incdtcat", "incdtcat_name"); _fkeymap.insert("incdtpriority", "incdtpriority_name"); _fkeymap.insert("incdtresolution","incdtresolution_name"); _fkeymap.insert("incdtseverity", "incdtseverity_name"); _fkeymap.insert("invchead", "invchead_invcnumber"); _fkeymap.insert("ipshead", "ipshead_name"); _fkeymap.insert("item", "item_number"); _fkeymap.insert("itemalias", "itemalias_number"); _fkeymap.insert("itemgrp", "itemgrp_name"); _fkeymap.insert("jrnluse", "jrnluse_number"); _fkeymap.insert("labelform", "labelform_name"); _fkeymap.insert("lang", "lang_name"); _fkeymap.insert("lbrrate", "lbrrate_code"); _fkeymap.insert("locale", "locale_code"); _fkeymap.insert("location", "location_name"); _fkeymap.insert("ls", "ls_number"); _fkeymap.insert("lsreg", "lsreg_number"); _fkeymap.insert("metric", "metric_name"); _fkeymap.insert("metricenc", "metricenc_name"); _fkeymap.insert("ophead", "ophead_name"); _fkeymap.insert("opsource", "opsource_name"); _fkeymap.insert("opstage", "opstage_name"); _fkeymap.insert("optype", "optype_name"); _fkeymap.insert("orderseq", "orderseq_name"); _fkeymap.insert("period", "period_name"); _fkeymap.insert("pkghead", "pkghead_name"); _fkeymap.insert("plancode", "plancode_code"); _fkeymap.insert("planord", "planord_number"); _fkeymap.insert("pohead", "pohead_number"); _fkeymap.insert("potype", "potype_name"); _fkeymap.insert("pr", "pr_number"); _fkeymap.insert("prftcntr", "prftcntr_number"); _fkeymap.insert("prj", "prj_number"); _fkeymap.insert("prjtask", "prjtask_number"); _fkeymap.insert("prodcat", "prodcat_code"); _fkeymap.insert("prospect", "prospect_number"); _fkeymap.insert("pschhead", "pschhead_number"); _fkeymap.insert("quhead", "quhead_number"); _fkeymap.insert("rahead", "rahead_number"); _fkeymap.insert("regtype", "regtype_code"); _fkeymap.insert("rev", "rev_number"); _fkeymap.insert("rjctcode", "rjctcode_code"); _fkeymap.insert("rsncode", "rsncode_code"); _fkeymap.insert("sale", "sale_name"); _fkeymap.insert("salehead", "salehead_number"); _fkeymap.insert("salescat", "salescat_name"); _fkeymap.insert("salesrep", "salesrep_number"); _fkeymap.insert("script", "script_name"); _fkeymap.insert("shift", "shift_number"); _fkeymap.insert("shipchrg", "shipchrg_name"); _fkeymap.insert("shipform", "shipform_name"); _fkeymap.insert("shiphead", "shiphead_number"); _fkeymap.insert("shiptoinfo", "shipto_name"); _fkeymap.insert("shipvia", "shipvia_code"); _fkeymap.insert("shipzone", "shipzone_name"); _fkeymap.insert("sitetype", "sitetype_name"); _fkeymap.insert("stdjrnl", "stdjrnl_name"); _fkeymap.insert("stdjrnlgrp", "stdjrnlgrp_name"); _fkeymap.insert("stdopn", "stdopn_number"); _fkeymap.insert("subaccnt", "subaccnt_number"); _fkeymap.insert("subaccnttype","subaccnttype_code"); _fkeymap.insert("tax", "tax_code"); _fkeymap.insert("taxauth", "taxauth_code"); _fkeymap.insert("taxreg", "taxreg_number"); _fkeymap.insert("taxtype", "taxtype_name"); _fkeymap.insert("terminal", "terminal_number"); _fkeymap.insert("terms", "terms_code"); _fkeymap.insert("todoitem", "todoitem_name"); _fkeymap.insert("tohead", "tohead_number"); _fkeymap.insert("uiform", "uiform_name"); _fkeymap.insert("uom", "uom_name"); _fkeymap.insert("uomtype", "uomtype_name"); _fkeymap.insert("url", "url_url"); _fkeymap.insert("usr", "usr_username"); _fkeymap.insert("vendaddrinfo","vendaddr_code"); _fkeymap.insert("vendinfo", "vend_number"); _fkeymap.insert("vendtype", "vendtype_code"); _fkeymap.insert("vohead", "vohead_number"); _fkeymap.insert("whsezone", "whsezone_name"); _fkeymap.insert("whsinfo", "warehous_code"); _fkeymap.insert("wo", "wo_number"); _fkeymap.insert("wrkcnt", "wrkcnt_code"); _fkeymap.insert("xsltmap", "xsltmap_name"); _fkeymap.insert("yearperiod", "yearperiod_start"); } for (int i = 0; i < model->record().count(); i++) { QString colname = model->record().field(i).name(); if (DEBUG) qDebug("looking for fkey to %s", qPrintable(colname)); if (colname.endsWith("curr_id")) model->setRelation(i, QSqlRelation("curr_symbol", "curr_id", "curr_abbr")); else if (colname.endsWith("cust_id")) model->setRelation(i, QSqlRelation("custinfo", "cust_id", "cust_number")); else if (colname.endsWith("shipto_id")) model->setRelation(i, QSqlRelation("shiptoinfo","shipto_id","shipto_name")); else if (colname.endsWith("vend_id")) model->setRelation(i, QSqlRelation("vendinfo", "vend_id", "vend_number")); else if (colname.endsWith("vendaddr_id")) model->setRelation(i, QSqlRelation("vendaddrinfo","vendaddr_id","vendaddr_code")); else if (colname.endsWith("warehous_id")) model->setRelation(i, QSqlRelation("whsinfo", "warehous_id", "warehous_code")); else if (colname.endsWith("_id")) { colname.replace(QRegExp(".*_([^_]+)_id$"), "\\1"); if (DEBUG) qDebug("%s is an id", qPrintable(colname)); if (! _fkeymap.value(colname, QString()).isEmpty()) { if (DEBUG) qDebug("setting relation(%s, %s, %s)", qPrintable(colname), qPrintable(colname + "_id"), qPrintable(_fkeymap.value(colname))); model->setRelation(i, QSqlRelation(colname, colname + "_id", _fkeymap.value(colname))); } } } }