DashboardWindow::DashboardWindow(QWidget *parent, bool isRelative, QString ID) : QWidget(parent), ui(new Ui::DashboardWindow) { ui->setupUi(this); //qDebug() << ID; m_RelativeID = ID; if (isRelative) { //qDebug() << "Is relative"; ui->stackedWidget->setCurrentIndex(1); on_pushButton_overview_clicked(); ui->pushButton_overview->setChecked(1); } else { ui->stackedWidget->setCurrentIndex(0); QSqlQueryModel *model = new QSqlQueryModel; QString query = "SELECT COUNT(*) FROM INMATE"; model->setQuery(query); ui->txtInmateCount->setText("Number of inmates: " + model->data(model->index(0, 0)).toString()); query = "SELECT COUNT(*) FROM RE_LATIVE"; model->setQuery(query); ui->txtRelativeCount->setText("Number of relatives: " + model->data(model->index(0, 0)).toString()); query = "SELECT COUNT(*) FROM OFFICER"; model->setQuery(query); ui->txtOfficerCount->setText("Number of officers: " + model->data(model->index(0, 0)).toString()); } }
ServiceBlock::ServiceBlock(int idC, QWidget *parent) : QDialog(parent), idCar(idC), ui(new Ui::ServiceBlock) { ui->setupUi(this); setCalendarColor(ui->deBegin->calendarWidget(),QColor(255,140,0)); setCalendarColor(ui->deEnd->calendarWidget(),QColor(255,140,0)); setCalendarColor(ui->deEvent->calendarWidget(),QColor(255,140,0)); setCalendarColor(ui->deGuarantee->calendarWidget(),QColor(255,140,0)); QSqlQueryModel * windTitle = new QSqlQueryModel(this); windTitle->setQuery(QString("SELECT Brand, Model, LicensePlate FROM car WHERE idCar = %1").arg(idCar)); this->setWindowTitle( QString("Naprawy - ") + windTitle->data(windTitle->index(windTitle->rowCount()-1,0)).toString() + QString(" ") + windTitle->data(windTitle->index(windTitle->rowCount()-1,1)).toString() + QString(" - ") + windTitle->data(windTitle->index(windTitle->rowCount()-1,2)).toString() ); connect(this,SIGNAL(saved()),this,SLOT(updateView()),Qt::DirectConnection); connect(this,SIGNAL(deleted()),this,SLOT(updateView())); // fill category combobox QStringList categoryList({QString("Silnik"),QString("Zawieszenie"),QString("Elektronika"), QString("Elektryka"),QString("Układ napędowy"),QString("Układ hamulcowy"), QString("Układ kierowniczy"),QString("Nadwozie")}); ui->cbCategory->addItems(categoryList); updateView(); isOpen = true; }
void MainWindow::on_buttonOpenCom_clicked(){ QSqlQueryModel *trackModel = (QSqlQueryModel*)ui->comboTrack->model(); QSqlQueryModel *vehicleModel = (QSqlQueryModel*)ui->comboVehicle->model(); if(ui->comboPortName->count()>0){ if(ui->comboTrack->currentIndex()!=-1){ if(ui->comboVehicle->currentIndex()!=-1){ if(!ui->newRaceNameText->text().trimmed().isEmpty()){ if(gsm->open(ui->comboPortName->currentText())){ logConsole->addToLog(LogConsole::INFO, "Porta seriale aperta correttamente"); ui->mainPanel->setCurrentIndex(1); ui->menuFile->setEnabled(false); ui->menuRecorder->setEnabled(true); ui->menuSommario->setEnabled(true); ui->menuImpostazioni->setEnabled(false); recordingSession->startNew( ui->newRaceNameText->text(), ui->raceDescText->toPlainText(), trackModel->data(trackModel->index(ui->comboTrack->currentIndex(),0)).toInt(), vehicleModel->data(vehicleModel->index(ui->comboTrack->currentIndex(),0)).toInt() ); showMaximized(); recordingViews->setup(); }else{ QMessageBox::critical(this, "Errore", gsm->getSerial()->errorString()); logConsole->addToLog(LogConsole::ERRORS, gsm->getSerial()->errorString()); } }else{ QMessageBox::critical(this, "Errore", "Il nome della gara non può essere vuoto!"); } }else{ QMessageBox::critical(this, "Errore", "Nessun veicolo selezionato!"); logConsole->addToLog(LogConsole::ERRORS, "Nessun veicolo selezionato!"); } }else{ QMessageBox::critical(this, "Errore", "Nessun circuito selezionato!"); logConsole->addToLog(LogConsole::ERRORS, "Nessuna circuito selezionato!"); } }else{ QMessageBox::critical(this, "Errore", "Impossibile trovare un dispositivo di ricezione!"); logConsole->addToLog(LogConsole::ERRORS, "Impossibile trovare un dispositivo di ricezione!"); } }
void AddOrEditActVnedrenia::on_radioButton_tema_rus_clicked() { if(this->sel==false) { QSqlQueryModel *combotema = new QSqlQueryModel(this); combotema = dal_studentsControl->getTemadiploma(); ui->comboBox_tema->setModel(combotema); ui->comboBox_tema->setModelColumn(1); ui->comboBox_tema->setCurrentIndex(-1); } else { QSqlQuery *query = new QSqlQuery; query = dal_studentsControl->getCurrentActVnedr(this->rec_id); ids_tema = query->value(3).toInt(); qDebug()<<ids_tema<<ids_tema2; if(ids_tema!=this->ids_tema2) { QSqlQueryModel *combotema = new QSqlQueryModel(this); combotema = dal_studentsControl->getTemadiploma(); ui->comboBox_tema->setModel(combotema); ui->comboBox_tema->setModelColumn(1); ui->comboBox_tema->setCurrentIndex(-1); return; } else { QSqlQueryModel *combotema = new QSqlQueryModel(this); combotema = dal_studentsControl->getTemadiploma(); ui->comboBox_tema->setModel(combotema); ui->comboBox_tema->setModelColumn(1); ui->comboBox_tema->setCurrentIndex(-1); for (int i = 0; i < ui->comboBox_tema->count(); i ++) { if (combotema->index(i, 0).data().toInt() == ids_tema) { ui->comboBox_tema->setCurrentIndex(i); ui->comboBox_tema->view()->setCurrentIndex(combotema->index(i, 0)); break; } } } } }
// Function to deleting record from table bool creatordialog::delete_record(QSqlRelationalTableModel* rmodel) { int row_to_delete; QModelIndexList selectedList = ui->tableView_CREATOR_1->selectionModel()->selectedRows(); for( int i=0; i<selectedList.count(); i++) { row_to_delete=selectedList.at(i).row(); } if(selectedList.isEmpty()) { QMessageBox::information(this,"Informacja","Nie zaznaczono wiersza do usunięcia."); return false; } QSqlQueryModel model; model.setQuery("SELECT * FROM "+relational_table_2+""); int id_first = model.data(model.index(row_to_delete, 0)).toInt(); int id_second = model.data(model.index(row_to_delete, 1)).toInt(); QSqlQuery query; if(relational_table_2=="Maszyny_has_Daneosobowe") { query.prepare("Delete from Maszyny_has_Daneosobowe where idMaszyny_MaszynyDaneosobowe=:first_id and idDaneosobowe_MaszynyDaneosobowe=:second_id"); } else if(relational_table_2=="Maszyny_has_Czesci") { query.prepare("Delete from Maszyny_has_Czesci where idMaszyny_MaszynyCzesci=:first_id and idCzesci_MaszynyCzesci=:second_id"); } query.bindValue(":first_id", id_first); query.bindValue(":second_id", id_second); if(query.exec()) { QMessageBox::information(this,"Informacja","USUNIĘTO"); rmodel->select(); count=false; return true; } else { QMessageBox::information(this,"Informacja",query.lastError().text()); return false; } }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // подключаемся к БД QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL"); db.setHostName("localhost"); db.setDatabaseName("postgres"); db.setUserName("postgres"); db.setPassword("12321"); if(!db.open()) { QMessageBox::critical( this, tr("Ошибка подключения к БД"), tr("Не удалось подключиться к БД.\n") + db.lastError().text() ); return; } else QMessageBox::information( this, tr("Всё огонь"), tr("Успешное подключение к БД.") ); // создаём модель запроса и выполняем его в ней QSqlQueryModel *model = new QSqlQueryModel; // запрашиваем имена полей таблицы model->setQuery("SELECT column_name FROM information_schema.columns " "WHERE information_schema.columns.table_name = " "'ВАША_ТАБЛИЦА';"); // создаём модель для комбо-бокса по числу строк из модели запроса QStandardItemModel *model4combo = new QStandardItemModel(model->rowCount(), 1, this); // переносим данные из модели запроса в модель для комбо-бокса QModelIndex index; // индекс для навигации по модели запроса for (int i = 0; i < model4combo->rowCount(); i++) { index = model->index(i, 0, QModelIndex()); // создаём элемент для добавления в модель комбо-бокса QStandardItem* item = new QStandardItem(model->data(index).toString()); // расставляем флаги, чтобы каждый элемент модели бы чекуемым item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); item->setData(Qt::Checked, Qt::CheckStateRole); // добавляем элемент в модель для комбо-бокса model4combo->setItem(i, 0, item); } // назначаем комбо-боксу нашу модель ui->comboBox->setModel(model4combo); }
void DetalleCompraVenta::populateClienteField() { QSqlQueryModel cliente; cliente.setQuery ("SELECT nombre,cuit FROM cliente ORDER BY nombre"); for(int i=0; i < cliente.rowCount(); i++) { ui->cliente->addItem( cliente.data(cliente.index(i,0)).toString(), QVariant( cliente.data(cliente.index(i,1)).toDouble())); } }
int BDTools::countRecord(QString table) { QSqlQuery query(sdb); QSqlQueryModel queryModel; query.exec("select count(*) from " + table); queryModel.setQuery(query); return queryModel.index(0,0).data().toInt(); }
void importDialog::selectionChanged(QItemSelection, QItemSelection) { ui->btnImportar->setEnabled(true); if(sender()==ui->listViewFP->selectionModel()) { QSqlQueryModel * model = qobject_cast<QSqlQueryModel*>(ui->listViewFP->model()); _empresaFp = model->record(ui->listViewFP->currentIndex().row()); _empDir = ui->txtRutaBD->text(); _empDir.append("/DBF"); _empDir.append(_empresaFp.value("CODEMP").toString().trimmed()); _contaDir = ui->txtRutaConta->text(); //_contaDir.append("/EMP"); //_contaDir.append(_empresaFp.value("CODEMP").toString().trimmed()); } else { QSqlQueryModel * model = qobject_cast<QSqlQueryModel*>(ui->listView->model()); int index = ui->listView->currentIndex().row(); _grupoMaya = model->record(index); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","grupo"); QString bd_name = model->data(model->index(index,2)).toString(); QString bd_host = model->data(model->index(index,5)).toString(); QString bd_user = model->data(model->index(index,6)).toString(); QString bd_pass = model->data(model->index(index,7)).toString(); int bd_port = model->data(model->index(index,8)).toInt(); db.setHostName(bd_host); db.setUserName(bd_user); db.setPassword(bd_pass); db.setPort(bd_port); db.setDatabaseName(bd_name); if(!db.open()) { QMessageBox::critical(this,tr("Error"),tr("No se puede conectar con la base de datos")); } } }
void ddmMinMaxFrictionFilterModel::updateMinMaxFrictions() { ddmDatabase& db = this->database(); QString sql = "SELECT MIN(f_mid) AS min_friction, MAX(f_mid) AS max_friction FROM ddm_frictions"; QSqlQueryModel* query = db.select( sql ); Q_ASSERT( !db.hasErrors() ); this->m_minFriction = query->data( query->index( 0, 0 ) ).toDouble(); this->m_maxFriction = query->data( query->index( 0, 1 ) ).toDouble(); qDebug() << "minFriction:" << this->m_minFriction; qDebug() << "maxFriction:" << this->m_maxFriction; }
void LoginDialog::login() { if (QSqlDatabase::database().open()) // megpróbáljuk megnyitni az adatbázis-kapcsolatot { QSqlQueryModel* model = new QSqlQueryModel(); model->setQuery("select user_id, name, password, level from user where user_id = '" + userNameEdit->text() + "' and password = '******'"); // lekérdezés model a megadott adatokra if (model->rowCount() > 0 && model->index(0, 0).data() == userNameEdit->text() && model->index(0, 2).data() == userPasswordEdit->text()) // ha sikerült a bejelentkeztetés { QMessageBox::information(this, trUtf8("Sikeres bejelentkezés!"), trUtf8("Üdvözöljük, ") + model->index(0, 1).data().toString()); mainWindow = new MainWindow(model->index(0, 3).data().toInt()); mainWindow->show(); // megnyitjuk a főablakot delete model; close(); // és bezárjuk a bejelentkeztető ablakot } else { QMessageBox::information(this, trUtf8("Sikertelen bejelentkezés!"), trUtf8("Kérem ellenőrizze a felhasználónevet és a jelszót!")); delete model; } } else { QMessageBox::information(this, trUtf8("Sikertelen bejelentkezés!"), trUtf8("Az adatbázis nem elérhető!\nLépjen kapcsolatba az adminisztrátorral!")); } }
void QSqlQueryModel_snippets() { { //! [16] QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("SELECT name, salary FROM employee"); model->setHeaderData(0, Qt::Horizontal, tr("Name")); model->setHeaderData(1, Qt::Horizontal, tr("Salary")); //! [17] QTableView *view = new QTableView; //! [17] //! [18] view->setModel(model); //! [18] //! [19] view->show(); //! [16] //! [19] //! [20] view->setEditTriggers(QAbstractItemView::NoEditTriggers); //! [20] } //! [21] QSqlQueryModel model; model.setQuery("SELECT * FROM employee"); int salary = model.record(4).value("salary").toInt(); //! [21] Q_UNUSED(salary); { //! [22] int salary = model.data(model.index(4, 2)).toInt(); //! [22] Q_UNUSED(salary); } for (int row = 0; row < model.rowCount(); ++row) { for (int col = 0; col < model.columnCount(); ++col) { qDebug() << model.data(model.index(row, col)); } } }
void DashboardWindow::on_pushButton_overview_clicked() { QSqlQueryModel *model = new QSqlQueryModel; QString query = "SELECT `INMATE`.`ID` AS ID, `INMATE`.`Lastname` AS `Last name`, `INMATE`.`Midname` AS `Middle name`, " "`INMATE`.`Firstname` as `First name`, " "`INMATE`.`Gender` AS Gender, `INMATE`.DOB AS DOB, Hair AS `Hair color`, Eyes AS `Eye color`, " "Eth AS `Ethnicity`, `INMATE`.`Addr` AS `Home address`, Reason AS Reason, Custody AS Custody, " "Availability AS Availability, BookIn AS Bookin, BookOut AS Bookout FROM `INMATE`, `RE_LATIVE` " "WHERE `INMATE`.`ID` = `RE_LATIVE`.`InmateID` AND `RE_LATIVE`.`ID` = N'" + m_RelativeID + "'"; model->setQuery(query); ui->tblRelatives->setModel(model); ui->tblRelatives->resizeColumnsToContents(); m_InmateID = model->data(model->index(0, 0)).toString(); }
void DetalleCompraVenta::populateLocalizacionField() { ui->localizacion->clear(); QSqlQuery query; query.prepare("SELECT id, lugar FROM localizacion WHERE _id = 1 OR cliente = :cliente"); query.bindValue(":cliente",ui->cliente->itemData(ui->cliente->currentIndex()).toLongLong()); query.exec(); QSqlQueryModel campos; campos.setQuery(query); for(int i=0; i < campos.rowCount(); i++) { ui->localizacion->addItem( campos.data(campos.index(i,1)).toString(), campos.data(campos.index(i,0)).toInt()); } }
//Ausleitung als csv-Datei void MainWindow::on_pushButton_clicked() { QSqlQueryModel *model = (QSqlQueryModel*)ui->listView->model(); QSqlRecord record = model->record(ui->listView->currentIndex().row()); QSqlField field_ID = record.field("ID"); DBank con; con.con_open(); QSqlQuery query(con.myDB); query.prepare("SELECT t.Vorname as Vorname, t.Nachname as Nachname, time(t.Endzeit-e.Startzeit, \"unixepoch\") from TEILNEHMER as t JOIN EVENT as e ON e.ID == t.EVENT_ID where e.ID = '"+field_ID.value().toString()+"' ORDER BY t.Endzeit ASC"); if(query.exec()) { QSqlQueryModel *model=new QSqlQueryModel(); model->setQuery(query); QString DB_Inhalt; int rows=model->rowCount(); int columns=model->columnCount(); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { DB_Inhalt += model->data(model->index(i,j)).toString(); DB_Inhalt += "; "; } DB_Inhalt += "\n"; } QString filename = QFileDialog::getSaveFileName(this,"Speichern unter","C://","All files (*.*);;ExcelFile(*.csv)"); QFile csvfile(filename); if(csvfile.open(QIODevice::WriteOnly|QIODevice::Truncate)) { QTextStream out(&csvfile); out<<DB_Inhalt; } csvfile.close(); } }
void StatisticalWnd::statistics() { QList<int> list; QList<QString>list_str; QList<float> cost; model->setTable("FamilyMember"); model->select(); for(int i=0; i<model->rowCount(); i++){ list += model->data(model->index(i,0)).toInt(); //MainID list_str += model->data(model->index(i,1)).toString(); //FamilyMember } for(int ii =0; ii<list.count();ii++) { QSqlQueryModel queryModel; queryModel.setQuery(QString("SELECT SUM(Money) FROM Account where %1").arg(filter)); cost.append(queryModel.data(queryModel.index(0,0)).toFloat()); qDebug()<<"filter:"<<filter; qDebug()<<cost[ii]; // for(int ii =0; ii<list.count(); ii++) // { // qDebug()<<(filter + QString(" and MainID = %1").arg(list.at(ii))); // model->setFilter(filter + QString(" and MainID = %1").arg(list.at(ii))); // model->select(); // for(int iii=0; iii<model->rowCount();iii++) // { // cost[ii] += model->data(model->index(3,iii)).toFloat(); // } QTableWidgetItem *item1 = new QTableWidgetItem; item1->setData(Qt::DisplayRole,list_str.at(ii)); QTableWidgetItem *item2 = new QTableWidgetItem; item2->setData(Qt::DisplayRole,cost[ii]); widget->setItem(ii,0,item1); widget->setItem(ii,1,item2); } }
void MainWindow::_onExpenseListItemSelected(QModelIndex index) { ExpenseSqlModel *expenseSqlModel = qobject_cast<ExpenseSqlModel*>(_ui->expenseListView->model()); _currentExpenseId = expenseSqlModel->data(index, ExpenseBook::IdRole).toLongLong(); QPixmap picture = expenseSqlModel->data(index, ExpenseBook::PictureRole).value<QPixmap>(); qlonglong spend = expenseSqlModel->data(index, ExpenseBook::SpendRole).toLongLong(); QString dateString = expenseSqlModel->data(index, ExpenseBook::DateRole).toString(); QString category = expenseSqlModel->data(index, ExpenseBook::CategoryRole).toString(); QString note = expenseSqlModel->data(index, ExpenseBook::NoteRole).toString(); _ui->pictureLabel->setOriginPixmap(picture); _ui->spendLineEdit->setText(QString::number(spend)); _ui->dateDateEdit->setDate(QDate::fromString(dateString, ExpenseBook::dateFormat())); QSqlQueryModel *categorySqlModel = _getCategorySqlModel(); _ui->categoryComboBox->setModel(categorySqlModel); for(int i=0; categorySqlModel->rowCount(); i++) { QModelIndex currentIndex = categorySqlModel->index(i, 0); if(categorySqlModel->data(currentIndex).toString() == category) { _ui->categoryComboBox->setCurrentIndex(i); break; } } _ui->noteTextEdit->setText(note); _ui->deletePushButton->setDisabled(false); _currentMode = EditExpenseMode; _ui->savePushButton->setText("修改"); _showExpenseWidget(); }
// 综合函数 void LzNTunnelsSynthesis::synthesis(ClearanceData& straightdata, ClearanceData& leftdata, ClearanceData& rightdata, int & straightnum, int & leftnum, int & rightnum, int & numofOutOfClearanceTunnels, int & numofOutOfClearanceBridges) { if (!hasinit) return; loadBaseClearanceTemplateData(this->outputtype); straightnum = 0; leftnum = 0; rightnum = 0; numofOutOfClearanceTunnels = 0; numofOutOfClearanceBridges = 0; // 初始化时检查需要初始化几个表格 // 【需求相关】 不管左(右)曲线段数量有多少,始终输出一个左(右)曲线限界表格 // 如果没有左转右转曲线,则一定包含直线段 straightdata.initMaps(); // 初始化高度,不可缺少 leftdata.initMaps(); // 初始化高度,不可缺少 rightdata.initMaps(); // 初始化高度,不可缺少 qDebug() << "size:" << task_clearance_ids.size(); // 临时存储当前帧的高度数据 std::list<_int64>::iterator it = task_clearance_ids.begin(); while (it != task_clearance_ids.end()) { // 是否超限 bool hasOutOfBaseClearance = false; for (int j = 0; j < 3; j++) // 3个OutputType均试一下 { ClearanceType tmptype; switch(j) { case 0: tmptype = Straight_Smallest; break; case 1: tmptype = LeftCurve_Smallest; break; case 2: tmptype = RightCurve_Smallest; break; default: break; } ClearanceData tempdata; tempdata.initMaps(); // 初始化高度,不可缺少 /**********读数据库限界值**********/ bool ret = ClearanceOutputDAO::getClearanceOutputDAOInstance()->DBDataToClearanceData(tempdata, (*it), tmptype); qDebug() << "DBDataToClearanceData" << ret << ", clearance_outputid=" << (*it); // 临时变量findInterMile()函数引用 tmptype = tempdata.getClearanceType(); //tempdata.setMinCenterHeightTunnelID(-1) int tmptunnelid = -1; QString tmptunnelname; QString tmpdate; QString tmplinename; // 根据采集隧道ID得到隧道基本ID TaskTunnelDAO::getTaskTunnelDAOInstance()->getTaskTunnelInfo((*it), tmptunnelid, tmptunnelname, tmpdate, tmplinename); tempdata.setTunnelID(tmptunnelid); if (ret) { switch (tmptype) { case Straight_Smallest: tempdata.updateToClearanceData(straightdata); straightnum++; break; case LeftCurve_Smallest: tempdata.updateToClearanceData(leftdata); leftnum++; break; case RightCurve_Smallest: tempdata.updateToClearanceData(rightdata); rightnum++; break; default:qDebug() << "can not find TYPE in task_tunnel_id" << (*it); break; } // 检查是否超限 if (!hasOutOfBaseClearance && hasinitBaseClearanceData) { hasOutOfBaseClearance = tempdata.checkLessThanStdSectionData(baseClearandeData); } //straightdata.showMaps(); } /*********************************/ } if (hasOutOfBaseClearance) { QSqlQueryModel * tunnelinfo = TaskTunnelDAO::getTaskTunnelDAOInstance()->getTaskTunnels_2((*it)); QModelIndex index; if (tunnelinfo->rowCount() > 0) { index = tunnelinfo->index(0, Tunnel_is_bridge); bool isbridge = tunnelinfo->data(index).toBool(); if (isbridge) numofOutOfClearanceBridges++; else numofOutOfClearanceTunnels++; } } it++; } }
void SongsQueryWideget::export_excel_clicked() { ///建立临时表映射 /// setCursor(Qt::WaitCursor); QSqlQueryModel *sqlquery = new QSqlQueryModel(this); QSqlQuery _query; MediaPagingQuery argu; getQueryCondition(argu); if(!_sql->queryMedia_All(argu, _query)) return; sqlquery->setQuery(_query); int rows = sqlquery->rowCount(); int columns = sqlquery->columnCount(); setCursor(Qt::ArrowCursor); QString desktopPath = QProcessEnvironment::systemEnvironment().value("USERPROFILE")+"\\Desktop"; QString fileName = QFileDialog::getSaveFileName(tableView_songsQuery, "保存", //QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), desktopPath, "Excel 文件(*.xls *.xlsx)"); QProgressDialog *progress = new QProgressDialog(this); progress->setLabelText("正在导出表格数据……"); progress->setRange(0, rows); progress->setModal(true); progress->setCancelButtonText("取消"); // progress->setMinimumSize(300, 50); progress->setMinimumWidth(400); progress->setAutoClose(true); if (fileName!="") { QAxObject *excel = new QAxObject; if (excel->setControl("Excel.Application")) //连接Excel控件 { excel->dynamicCall("SetVisible (bool Visible)","false");//不显示窗体 excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改,是否保存”的提示 QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合 workbooks->dynamicCall("Add");//新建一个工作簿 QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿 QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1); // //数据区 for(int i=0; i<rows; i++) { for (int j=0;j<columns; j++) { QModelIndex index = sqlquery->index(i, j); QString text = index.data().toString(); // table->item(i,j)?table->item(i,j)->text():"" worksheet->querySubObject("Cells(int,int)", i+1, j+1)->dynamicCall("SetValue(const QString&)", text); } QString label_text = QString("正在导出%1行……").arg(i+1); progress->setLabelText(label_text); progress->setValue(i+1); if(progress->wasCanceled()) { break; } } workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(fileName));//保存至fileName workbook->dynamicCall("Close()");//关闭工作簿 //关闭excel excel->dynamicCall("Quit (void)"); delete excel; excel=NULL; QMessageBox box(QMessageBox::Question, "完成", "文件已经导出,是否现在打开?"); box.setStandardButtons(QMessageBox::Yes|QMessageBox::No); box.setButtonText(QMessageBox::Yes, "确定(&Q)"); box.setButtonText(QMessageBox::No, "取消(&C)"); if(box.exec() == QMessageBox::Yes) // if (QMessageBox::question(NULL,"完成","文件已经导出,是否现在打开?",QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes) { QString local_path = QString("file:///") + fileName; QDesktopServices::openUrl(QUrl(local_path, QUrl::TolerantMode)); //QDir::toNativeSeparators(fileName))); } } else { QMessageBox::warning(NULL,"错误","未能创建 Excel 对象,请安装 Microsoft Excel。",QMessageBox::Apply); } } // progress->close(); }
void Dialog_editPersInfo::accept() { ui->buttonBox->setDisabled(true); if (DEBUGMODE) qDebug() << "editPersInfo dialog accepted:"; QString name = ui->persName->text(); QString surname = ui->persSurname->text(); QString birthday = ui->persBirthDate->date().toString("yyyy-MM-dd"); QString education = ui->persEdu->text(); if (DEBUGMODE) qDebug() << "data to create/update:" << name << surname << birthday << education; QString queryText; bool execPipeResultStatus = true; // INFO UPDATE if (persId == -1) { queryText = QString( "insert into \"Myronenko_O\".person " "(per_name, per_surname, birthday, education) " "values('%1', '%2', '%3', '%4');").arg(name).arg(surname).arg(birthday).arg(education); execPipeResultStatus = execPipeResultStatus && db->executeQuery(queryText, "admin", this, -1); queryText = QString( "select \"Id_person\" " "from \"Myronenko_O\".person " "where per_name = '%1' " "and per_surname = '%2';").arg(name).arg(surname); QSqlQueryModel *modelNewPosition = db->getQueryModel(queryText); QModelIndex index = modelNewPosition->index(0, 0); persId = index.data(Qt::DisplayRole).toInt(); } else { queryText = QString( "delete from \"Myronenko_O\".personal_skills " "where \"Id_person\" = %1;").arg(persId); execPipeResultStatus = execPipeResultStatus && db->executeQuery(queryText, "admin", this, -1); queryText = QString( "update \"Myronenko_O\".person set " "per_name = '%1', " "per_surname = '%2', " "birthday = '%3', " "education = '%4' " "where \"Id_person\" = %5;").arg(name).arg(surname).arg(birthday).arg(education).arg(persId); if (DEBUGMODE) qDebug() << "update person" << persId << "query:" << queryText; execPipeResultStatus = execPipeResultStatus && db->executeQuery(queryText, "admin", this, -1); } // SKILLS UPDATE for (int i=0; i < skills.length(); i++) { queryText = QString( "insert into \"Myronenko_O\".personal_skills (\"Id_person\", \"Id_skill\") " "values (%1, %2);").arg(persId).arg(skills[i]); qDebug() << queryText; execPipeResultStatus = execPipeResultStatus && db->executeQuery(queryText, "admin", this, -1); }; if (execPipeResultStatus) { if (persId == -1) { db->showExecutionResultStatus(1); } else { db->showExecutionResultStatus(2); } }; lastCreatedPersId = persId; this->accepted(); this->close(); ui->buttonBox->setEnabled(true); }
CarBlock::CarBlock(bool toAdd, int id, QString name, QString model, QString licensePlate, QDate inspectionDate, QDate insuranceDate, int mileage, Status status, QString photoPath, bool isVisible, int oil, QWidget *parent): QWidget(parent), ui(new Ui::CarBlock), idCar(id), isAddBlock(toAdd) { ui->setupUi(this); if(!isAddBlock){ ui->lblLicensePlate->setText(licensePlate); ui->lblCarName->setText(name + QString(" ") + model); ui->lblMileage->setText(QString::number(mileage)); setVisibleButton(isVisible); } else if(isAddBlock){ ui->btnReserve->setVisible(false); ui->btnAddInspection->setVisible(false); ui->btnAddInsurance->setVisible(false); ui->btnAddLicensePlate->setVisible(false); ui->btnAddMileage->setVisible(false); ui->lblStatus->setVisible(false); ui->btnViewNotes->setVisible(false); ui->btnOil->setVisible(false); ui->btnAddLicensePlate->setVisible(false); ui->btnAddMileage->setVisible(false); ui->lblPersonImage->setVisible(false); ui->btnViewRepairs->setVisible(false); ui->lblMileage->setReadOnly(false); ui->lblCarName->setReadOnly(false); ui->lblLicensePlate->setReadOnly(false); ui->btnRemove->setIcon(QIcon(":/images/images/add.png")); ui->btnPDF->setVisible(false); QRegExp rx("^\\w+\\s\\w+$"); ui->lblCarName->setValidator(new QRegExpValidator(rx, this)); setVisibleButton(isVisible); } ui->lblPhoto->setPixmap(QPixmap(photoPath)); carPhotoPath = photoPath; ui->dateEditInspection->setDate(inspectionDate); ui->dateEditInsurance->setDate(insuranceDate); if(!isAddBlock) { QDate tmp; tmp = QDate::currentDate().addDays(7); if(tmp >= inspectionDate) ui->lblInspectionImage->setPixmap(QPixmap(":/images/images/inspection_warning.png")); else ui->lblInspectionImage->setPixmap(QPixmap(":/images/images/inspection.png")); if(tmp >= insuranceDate) ui->lblInsuranceImage->setPixmap(QPixmap(":/images/images/insurance_warning.png")); else ui->lblInsuranceImage->setPixmap(QPixmap(":/images/images/insurance.png")); if(oil-mileage <=100) ui->btnOil->setIcon(QIcon(":/images/images/oil_warning.png")); else ui->btnOil->setIcon(QIcon(":/images/images/oil.png")); } setStatus(status); if(status && isVisible) { QSqlQueryModel * historyTable = new QSqlQueryModel(this); historyTable->setQuery(QString("SELECT Name, Surname, Destination FROM history WHERE idCar = %1 AND End IS NULL").arg(idCar)); ui->lblPerson->setText( historyTable->data(historyTable->index(historyTable->rowCount()-1,0)).toString() + QString(" ") + historyTable->data(historyTable->index(historyTable->rowCount()-1,1)).toString() + QString(" ") + historyTable->data(historyTable->index(historyTable->rowCount()-1,2)).toString() ); delete historyTable; } else { ui->lblPersonImage->setVisible(false); ui->lblPerson->setVisible(false); } if(!isVisible) ui->btnReserve->setVisible(false); }
void ServiceBlock::on_pbSave_clicked() { if(Database::isOpen()) { // insert new repair if(!isDateCorrect()) return; if(ui->lvServices->currentIndex().data(Qt::DisplayRole ).toString() == "Dodaj naprawę ...") { QSqlQuery qry; qry.prepare("INSERT INTO service(Name,ComponentCategory,EventDate,GuaranteeDate," "BeginDate,EndDate,Cost,Notes,idCar)" "VALUES(:_Name,:_ComponentCategory,:_EventDate,:_GuaranteeDate," ":_BeginDate,:_EndDate,:_Cost,:_Notes,:_idCar)"); if(ui->leName->text()!="") qry.bindValue(":_Name", ui->leName->text()); qry.bindValue(":_ComponentCategory", ui->cbCategory->currentText()); qry.bindValue(":_EventDate", ui->deEvent->date()); qry.bindValue(":_GuaranteeDate", ui->deGuarantee->date()); qry.bindValue(":_BeginDate", ui->deBegin->date()); qry.bindValue(":_EndDate", ui->deEnd->date()); qry.bindValue(":_Cost", ui->leCost->text() ); qry.bindValue(":_Notes", ui->teNotes->toPlainText()); qry.bindValue(":_idCar", idCar); if(!qry.exec()) QMessageBox::warning(this,tr("Uwaga!"),"Dodawanie nie powiodło się.\nERROR: "+qry.lastError().text()+""); else { QSqlQueryModel lastInserted; lastInserted.setQuery(QString("SELECT * FROM service WHERE idCar = %1 WHERE idCar = 1 AND idService = (SELECT MAX(idService) FROM service);").arg(idCar)); lwiVector.push_back(new QListWidgetItem(ui->leName->text())); lwiVector.back()->setData(0, lastInserted.index(0,0).data().toInt()); clearWidgets(); ui->lvServices->item(0)->setSelected(true); updateView(); QMessageBox::information(this,"Informacja","Dodano naprawę!"); } } // update repair else { QSqlQuery qry; qry.prepare("UPDATE service SET Name=:_Name,ComponentCategory=:_ComponentCategory," "EventDate=:_EventDate,GuaranteeDate=:_GuaranteeDate," "BeginDate=:_BeginDate,EndDate=:_EndDate,Cost=:_Cost,Notes=:_Notes WHERE idService=:_idS"); if(ui->leName->text()!="") qry.bindValue(":_Name", ui->leName->text()); qry.bindValue(":_ComponentCategory", ui->cbCategory->currentText()); qry.bindValue(":_EventDate", ui->deEvent->date()); qry.bindValue(":_GuaranteeDate", ui->deGuarantee->date()); qry.bindValue(":_BeginDate", ui->deBegin->date()); qry.bindValue(":_EndDate", ui->deEnd->date()); qry.bindValue(":_Cost", ui->leCost->text() ); qry.bindValue(":_Notes", ui->teNotes->toPlainText()); qry.bindValue(":_idS", idService); if( !qry.exec() ) QMessageBox::warning(this,tr("Uwaga!"),"Aktualizacja nie powiodła się.\nERROR: "+qry.lastError().text()+""); else { QMessageBox::information(this,tr("Informacja"),tr("Zaktualizowano!")); clearWidgets(); emit saved(); } } } else QMessageBox::critical(this,tr("Błąd!"), tr("Utracono połączenie z bazą danych!")); }
EditArticle::EditArticle(QString artID,QWidget *parent) : QDialog(parent), ui(new Ui::editarticle) { ui->setupUi(this); QString articleQuery = "SELECT * FROM article where id = " + artID; QString authorsQuery = "SELECT * from author where article_id = " + artID; curArt = artID; QSqlQuery qry; qry.prepare(articleQuery); //fill in tableview items for authors model = new QStandardItemModel(0,2); ui->tableView->setModel(model); QSqlQueryModel *sqlmodel = new QSqlQueryModel; sqlmodel->setQuery(authorsQuery); model->setHeaderData(0,Qt::Horizontal,tr("Author")); model->setHeaderData(1,Qt::Horizontal,tr("Affiliation")); for(int i=0; i < sqlmodel->rowCount();i++) { QString authstr = sqlmodel->data(sqlmodel->index(i,1)).toString(); QString affilstr = sqlmodel->data(sqlmodel->index(i,2)).toString(); QStandardItem *auth = new QStandardItem(authstr); QStandardItem *affil = new QStandardItem(affilstr); model->appendRow( StandardItemList() << auth << affil ); } ui->tableView->setModel(model); QHeaderView* header = ui->tableView->horizontalHeader(); header->setSectionResizeMode(QHeaderView::Stretch); ui->tableView->resizeColumnsToContents(); if (!qry.exec() || !qry.first()) { // SQL error (for example, if the table doesn't exist) QMessageBox msgBox; msgBox.critical(0,"Error","No article selected, please select and try again"); msgBox.setFixedSize(500,200); } else { QString journalID = qry.value(4).toString(); QString article = qry.value(1).toString(); QString volume = qry.value(5).toString(); QString issue = qry.value(6).toString(); QString parser = qry.value(3).toString(); QString yM= "SELECT month,year from journal_issue where journal_id = " + journalID + " and volume = " + volume + " and issue = " + issue; QSqlQuery yMquery,jQuery; qDebug()<<yM; yMquery.exec(yM); yMquery.next(); jQuery.exec("SELECT name from journal where id = " + journalID); jQuery.next(); QString journal = jQuery.value(0).toString(); QString month = Utility::intToMonth(yMquery.value(0).toInt()); QString year = yMquery.value(1).toString(); ui->lineEdit->setText(article); this->setWindowTitle("Article - " + article); ui->journalLabel->setText("Journal: " + journal); ui->volumeLabel->setText("Volume: " + volume); ui->issueLabel->setText("Issue: " + issue); ui->monthLabel->setText("Month: " + month); ui->yearLabel->setText("Year: " + year); } journalSetup(""); }
AddOrEditActVnedrenia::AddOrEditActVnedrenia(QWidget *parent, int select, int id) : QDialog(parent), ui(new Ui::AddOrEditActVnedrenia) { ui->setupUi(this); this->stud_id=0; this->group_id=0; this->tema_id=0; if (! dal_main->checkConnection()) { QMessageBox::warning(this, tr("Ошибка подключения"), tr("Соединение не установлено")); throw std::exception(); } this->isEdit = false; dal_studentsControl = new Dal_studentsControl(this); QSqlQueryModel *comboGroup = new QSqlQueryModel(this); comboGroup = dal_studentsControl->getComboGroup(0); ui->dateEdit->setDate(QDate::currentDate()); ui->comboBox_grupa->setModel(comboGroup); ui->comboBox_grupa->setModelColumn(1); ui->comboBox_grupa->setCurrentIndex(-1); ui->label_error->setVisible(false); QSqlQueryModel *comboStudent = new QSqlQueryModel(this); comboStudent = dal_studentsControl->getStudentGroup(this->group_id); ui->comboBox_student->setModel(comboStudent); ui->comboBox_student->setModelColumn(1); ui->comboBox_student->setCurrentIndex(-1); QSqlQueryModel *combotema = new QSqlQueryModel(this); combotema = dal_studentsControl->getTemadiploma(); ui->comboBox_tema->setModel(combotema); ui->comboBox_tema->setModelColumn(1); ui->comboBox_tema->setCurrentIndex(-1); if (select == 1) { this->sel=false; this->setWindowTitle(tr("Добавить новую запись")); } else { this->isEdit = true; this->sel=true; this->setWindowTitle(tr("Редактирование записи")); this->rec_id = id; int ids_groups; int ids_student; QSqlQuery *query = new QSqlQuery; query = dal_studentsControl->getCurrentActVnedr(this->rec_id); ids_groups = query->value(2).toInt(); ids_student = query->value(1).toInt(); ids_tema = query->value(3).toInt(); this->ids_tema2 = ids_tema; comboStudent = dal_studentsControl->getStudentGroup(ids_groups); ui->comboBox_student->setModel(comboStudent); ui->comboBox_student->setModelColumn(1); ui->comboBox_student->setCurrentIndex(-1); ui->lineEdit_nomer_acta->setText(query->value(6).toString()); ui->lineEdit_predpriyatie->setText(query->value(7).toString()); ui->dateEdit->setDate(query->value(8).toDate()); ui->plainTextEdit_dopolnenia->setPlainText(query->value(11).toString()); for (int j = 0; j < ui->comboBox_grupa->count(); j ++) { if (comboGroup->index(j, 0).data().toInt() == ids_groups) { ui->comboBox_grupa->setCurrentIndex(j); ui->comboBox_grupa->view()->setCurrentIndex(comboGroup->index(j, 0)); break; } } for (int i = 0; i < ui->comboBox_student->count(); i ++) { if (comboStudent->index(i, 0).data().toInt() == ids_student) { ui->comboBox_student->setCurrentIndex(i); ui->comboBox_student->view()->setCurrentIndex(comboStudent->index(i, 0)); break; } } for (int i = 0; i < ui->comboBox_tema->count(); i ++) { if (combotema->index(i, 0).data().toInt() == ids_tema) { ui->comboBox_tema->setCurrentIndex(i); ui->comboBox_tema->view()->setCurrentIndex(combotema->index(i, 0)); break; } } } }
void Dialog_editPersInfo::showInpValues() { QString queryText; QModelIndex index; //------------- // PERSINFO BLOCK //------------- if (persId != -1) { queryText = QString("select * from \"Myronenko_O\".person where \"Id_person\" = %1;").arg(persId); QSqlQueryModel *modelPerson = db->getQueryModel(queryText); index = modelPerson->index(0, 1); QString name = index.data(Qt::DisplayRole).toString(); ui->persName->setText(name); index = modelPerson->index(0, 2); QString surname = index.data(Qt::DisplayRole).toString(); ui->persSurname->setText(surname); index = modelPerson->index(0, 3); QDate birthday =index.data(Qt::DisplayRole).toDate(); ui->persBirthDate->setDate(birthday); index = modelPerson->index(0, 4); QString education = index.data(Qt::DisplayRole).toString(); ui->persEdu->setText(education); } //------------- // LIST SKILLS BLOCK //------------- if (persId != -1) { queryText = QString( "select skill_name, skill_description, per_skills.\"Id_person\", per_skills.\"Id_skill\" " "from \"Myronenko_O\".personal_skills per_skills " "join \"Myronenko_O\".skills " "on per_skills.\"Id_skill\" = skills.\"Id_skill\" " "where per_skills.\"Id_person\" = %1 " "order by skill_name;").arg(persId); QSqlQueryModel *modelPersonSkills = db->getQueryModel(queryText); int skillsCount = modelPersonSkills->rowCount(); for (int i=0; i < skillsCount; i++) { index = modelPersonSkills->index(i, 0); QString skillName = index.data(Qt::DisplayRole).toString(); index = modelPersonSkills->index(i, 3); int skillId = index.data(Qt::DisplayRole).toInt(); inserSkillIntoList(skillName, skillId); } } //------------- // EDIT SKILLS BLOCK //------------- queryText = "select \"Id_skill\", skill_name " "from \"Myronenko_O\".skills " "order by skill_name;"; modelAllSkills = db->getQueryModel(queryText); int allSkillsCount = modelAllSkills->rowCount(); ui->comboBox_selectSkill->clear(); for (int i=0; i < allSkillsCount; i++) { index = modelAllSkills->index(i, 0); if (persId == -1 || skills.indexOf(index.data(Qt::DisplayRole).toInt()) == -1) { index = modelAllSkills->index(i, 1); ui->comboBox_selectSkill->addItem(index.data(Qt::DisplayRole).toString()); } } }
QSqlQueryModel *KjoMsgDbLayer::find_rec(QString kword) { // строка запроса QString query = "SELECT column_name " "FROM information_schema.columns " "WHERE table_name = 'records_view' " "AND table_schema = 'kjo' " "AND (data_type = 'character' " "OR data_type = 'character varying' " "OR data_type = 'text');"; // создание процесса на выполнение запроса DbProcess *getTextFields = new DbProcess( dbptSqlCommand, "Запрос имён текстовых полей", query ); // запуск процесса getTextFields->startDbProcess(); // проверка выполнения запроса if(!getTextFields->getSqlResultIsActive()) return NULL; // индекс нужен для навигации по модели результатов запроса QModelIndex index; // модель для сохранения результатов запроса имён текстовых полей QSqlQueryModel *tempModel = getTextFields->getSqlResultToModel(); delete getTextFields; // больше оно нам не нужно // сюда сложим полученные имена текстовых полей QStringList textFields; // возьмём из каждой строки модели (столбец у нас один) имя текстового поля for(int i = 0; i < tempModel->rowCount(); i++) { index = tempModel->index(i, 0, QModelIndex()); textFields << tempModel->data(index).toString(); } // можно посмотреть, какие поля в запрашиваемой таблице оказались текстовыми // qDebug() << textFields; // теперь начинаем искать по ключевому слову // суть такова: составить запрос с LIKE для каждого из найденных // текстовых полей // возьмём ключевое слово QString keyword = kword; // строка запроса query = "SELECT * FROM kjo.records_view WHERE "; // заполняем запрос именами полей из нашего списка for(int i = 0; i < textFields.count(); i++) { query += textFields.at(i) + " LIKE '%" + keyword + "%' OR "; } // отрезаем последний OR и ставим ; query.chop(4); query += ";"; // можно посмотреть строку запроса // qDebug() << query; // создание процесса на выполнение запроса DbProcess *templateSearch = new DbProcess( dbptSqlCommand, "Поиск по ключевому слову", query ); // запуск процесса templateSearch->startDbProcess(); // проверка выполнения запроса if(!templateSearch->getSqlResultIsActive()) return NULL; else return templateSearch->getSqlResultToModel(); }