本文整理汇总了C++中QSqlQueryModel::data方法的典型用法代码示例。如果您正苦于以下问题:C++ QSqlQueryModel::data方法的具体用法?C++ QSqlQueryModel::data怎么用?C++ QSqlQueryModel::data使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QSqlQueryModel
的用法示例。
在下文中一共展示了QSqlQueryModel::data方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: categoryList
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;
}
示例2: populateClienteField
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()));
}
}
示例3: on_buttonOpenCom_clicked
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!");
}
}
示例4: populateLocalizacionField
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());
}
}
示例5: delete_record
// 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;
}
}
示例6: information
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);
}
示例7: selectionChanged
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"));
}
}
}
示例8: updateMinMaxFrictions
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;
}
示例9: QSqlQueryModel_snippets
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));
}
}
}
示例10: on_pushButton_overview_clicked
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();
}
示例11: QWidget
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());
}
}
示例12: on_pushButton_clicked
//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();
}
}
示例13: statistics
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);
}
}
示例14: _onExpenseListItemSelected
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();
}
示例15: synthesis
// 综合函数
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++;
}
}
//.........这里部分代码省略.........
开发者ID:fanxiang090909,项目名称:Railway-Tunnel-Construction-Dlearance-Measure-LanZhou,代码行数:101,代码来源:LzSynth_n.cpp