示例#1
1
void CDeleteAclTask::updateRules(int ruleId,int cmdType)
{
	QSqlTableModel model;
	model.setTable("aclrules");
	QString filter1=QString("id=%1").arg(ruleId);
	model.setFilter(filter1);
	model.select();

	if (model.rowCount()==1)
	{
		QSqlRecord record=model.record(0);
		record.setValue("cmdtype",cmdType);
		model.setRecord(0,record);
	}

	model.submitAll();
	//QString error=model.lastError().text();
	//QMessageBox::information(this, tr("information"), error);
}
示例#2
0
void MainWindow::importData()
{
	int exam_id;
	QString dataFileName = QFileDialog::getOpenFileName(this,tr("Import Data From a CSV File"),QDir::homePath(),tr("CSV File (*.csv)"));
	if(dataFileName.isEmpty())
		return;
	QFile dataFile(dataFileName);
	if(!dataFile.open(QIODevice::ReadOnly))
	{
		QMessageBox::critical(this,tr("Open File Failed"),tr("Cannot open selected file"));;
		return;
	}

	QSqlTableModel* student = m_scoreView->studentListModel();
	QSqlTableModel* exam = m_scoreView->examListModel();
	QSqlRelationalTableModel* score = m_scoreView->scoreListModel();

	QFileInfo tmp(dataFileName);
	QString exam_name = tmp.baseName();
	exam->setFilter(QString("name = \'%1\'").arg(exam_name));
	if(exam->rowCount() == 1)
	{
		QSqlRecord rq = exam->record(0);
		exam_id = rq.value("id").toInt();
	}
	else
	{
		exam->insertRow(0);
		exam->setData(exam->index(0,Global::Exam_Name),exam_name);
		exam->submitAll();
		exam->setFilter(QString("name = \'%1\'").arg(exam_name));
		QSqlRecord rq = exam->record(0);
		exam_id = rq.value("id").toInt();
	}

	QHash<QString,int> studentMap;
	for(int row = 0;row < student->rowCount();++row)
		studentMap.insert(student->data(student->index(row,1)).toString(),student->data(student->index(row,0)).toInt());

	QTextStream in(&dataFile);
	QString record = in.readLine();
	QStringList candidate_seps;
	candidate_seps << ";" << "," << "\t" << " ";
	QString real_sep;
	bool is_legal = false;
	QStringList cols;
	foreach(real_sep, candidate_seps)
	{
		cols = record.split(real_sep);
		if(cols.size() == 11)
		{
			is_legal = true;
			break;
		}
	}
void CollectionTreeWidget::showChildrenOf(QModelIndex index) {
    CollectionTreeWidgetItem *item = (CollectionTreeWidgetItem*)itemFromIndex(index);

    // If the item pressed was an artist, add albums
    if (item->getNodeLevel() == LevelArtist) {
        QString artist = item->text(0).toUtf8();

        // Looks for artist id
        QString artistId = QString::number(item->getId());

        // Looks for artist albums
        QSqlTableModel *albumModel = service->albumModel();
        albumModel->setFilter("id_artist = " + artistId);
        albumModel->select();

        while (albumModel->canFetchMore()) albumModel->fetchMore();
        int total = albumModel->rowCount();

        for (int i = 0; i < total; i++) {
            QString album = albumModel->record(i).value(albumModel->fieldIndex("title")).toString();
            unsigned int id = albumModel->record(i).value(albumModel->fieldIndex("id")).toInt();
            addAlbum(artist, album, id);
        }

        delete albumModel;
    }
    // If the item pressed was an album, add songs
    else if (item->getNodeLevel() == LevelAlbum) {
        QString albumId = QString::number(item->getId());

        QSqlTableModel *musicModel = service->musicModel();
        musicModel->setFilter("id_album = " + albumId);
        musicModel->setSort(musicModel->fieldIndex("track_number"), Qt::AscendingOrder);
        musicModel->select();

        while (musicModel->canFetchMore()) musicModel->fetchMore();
        int total = musicModel->rowCount();

        for (int i = 0; i < total; i++) {
            QString path = musicModel->record(i).value(musicModel->fieldIndex("path")).toString();
            unsigned int id = musicModel->record(i).value(musicModel->fieldIndex("id")).toInt();

            Music *music = new Music(QUrl(path));
            addMusic(music, id);
            delete music;
        }
    }

    expand(index);
}
bool DatabaseHandler::writeCensus(census * obj) {
    qDebug() << "Writing object data to database.";
    QSqlTableModel table;
    table.setTable("census");
    table.setFilter("rcns_id=" + QString::number(obj->id) + " AND usr='******'");
    table.select();
    // get record structure from db
    QSqlRecord record(table.record());
    // initialize record with census-structure values
    setRecordTable(&record, obj);

    // insert or update records in db
    if (table.rowCount() == 0) { //INSERT
        qDebug() << "Insert!";
        // remove first entry of record
        // auto increment of id is handled by postgres
        record.remove(0);
        bool done = table.insertRecord(-1,record);
        qDebug() << table.lastError();
        return done;
    } else { //UPDATE
        qDebug() << "Update!";
        record.setValue("fcns_id",table.record(0).value(0).toInt());
        bool check = true;
        check = check && table.setRecord(0, record);
        check = check && table.submitAll();
        qDebug() << table.lastError();
        return check;
    }
    return true;
}
//Compare button
void MainWindow::on_pushButton_clicked()
{

    //Create a Table Model
    QString q_filter = QString("");
    QList<QString> rows;
    QSqlTableModel *model = new QSqlTableModel;
    model->setTable("important");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    for(int i = 0; i < ui->listWidget_2->count(); i++)
    {
        //Use a regex to extract the ID from the row
        QString row_id = ui->listWidget_2->item(i)->text();
        QRegExp rx("(^\\d+)");
        rx.indexIn(row_id);
        row_id = rx.cap(1);

        //Build the filter for the Table Model
        if(i > 0)
            q_filter = q_filter + " or ";
        q_filter = QString(q_filter + "parentTableFK = " + row_id);

    }

    //Run the query, populate the table
    model->setFilter(q_filter);
    model -> select();

    this->ui->tableView->setModel(model);
    this->ui->tableView->show();
}
int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
    db.setDatabaseName( "testdatabase.db" );

    if( !db.open() )
    {
        qDebug() << db.lastError();
        qFatal( "Failed to connect." );
    }

    QSqlQuery qry;
    qry.prepare( "CREATE TABLE IF NOT EXISTS names (id INTEGER UNIQUE PRIMARY KEY, "
            "firstname VARCHAR(30), "
            "lastname VARCHAR(30))" );
    if( !qry.exec() )
    {
        qDebug() << qry.lastError();
        qFatal( "Failed to create the table" );
    }

    qry.prepare( "INSERT INTO names (id, firstname, lastname) "
            "VALUES (:id, :firstname, :lastname)" );
    qry.bindValue( ":id", 1 );
    qry.bindValue( ":firstname", "John" );
    qry.bindValue( ":lastname", "Doe" );
    if( !qry.exec() )
    {
        qDebug() << qry.lastError();
        qFatal( "Failed to insert" );
    }

    QSqlTableModel *model = new QSqlTableModel();

    model->setTable( "names" );
    model->setFilter( "lastname = 'Doe'" );
    model->select();

    // if removeColumn is enabled, the table won't be editable, this
    // is a bug under this old version
    //model->removeColumn( 0 );

    QTableView *view = new QTableView();
    //view->setColumnHidden( 0, true );
    view->setModel( model );
    view->show();

    /*
    QSqlQueryModel *model = new QSqlQueryModel();
    model->setQuery( "SELECT firstname, lastname FROM names" );

    QTableView *view = new QTableView();
    view->setModel( model );
    view->show();
    */

    return app.exec();
}
示例#7
0
void TableWindow::Prepare(QString filter)
{
    Database database = Database::getInstance();
    QSqlDatabase db = database.getDatabase();

    if (db.open()) {
        Users *user = new Users();
        if (user->userCanEdit(login)) {
            QSqlTableModel *model = new QSqlTableModel();
            model->setTable("money_management");
            model->setFilter(filter);
            model->select();
            model->setEditStrategy(QSqlTableModel::OnFieldChange);
            ui->tableView->setModel(model);
        }
        else {
            QSqlQueryModel *model = new QSqlQueryModel();
            QString query = "select * from money_management";

            if (!filter.isEmpty()) {
                query +=  " where " + filter;
            }

            model->setQuery(query, db);
            ui->tableView->setModel(model);
        }
    }
    else {
        qDebug() << "Open db error.";
    }
}
示例#8
0
void DlgLogin::on_buttonBox_accepted()
{
    try {

            QByteArray byteArray = ui->txtPassword->text().toUtf8();
            const char* cString = byteArray.constData();
            QString pwd=QString(QCryptographicHash::hash(cString, QCryptographicHash::Md5).toHex());
            QSqlTableModel personal;
            personal.setTable("personal");
            QString filter=QString("login='******' and pwd='%2'").arg(ui->txtUsuario->text().trimmed()).arg(pwd);
            personal.setFilter(filter);
            personal.select();
            if(personal.rowCount()>0){
                MainWindow* w=(MainWindow *) this->parent();
                w->statusBar()->showMessage(tr("Ready"));
                QSqlRecord record=personal.record(0);
                QString userName= QString("%1 %2").arg(record.value("nombre").toString()).arg(record.value("paterno").toString());
                w->setUserName(userName.toUpper());
                qApp->setProperty("user",record.value("id"));
                qApp->setProperty("profile",record.value("perfil_id"));
//                qDebug()<< qApp->property("profile");
            }else{
                ui->lblStateLogin->setText("Usuario o Contraseña errada");
                this->setVisible(true);
            }
    } catch (...) {
        QMessageBox::information(this, "info", "We are in throwExcept()",
                                 QMessageBox::Ok);
    }

}
示例#9
0
void MaterialSaverDB::saveTemplateChapter( StockMaterial* tmpl )
{
    if( ! tmpl ) {
        kDebug() << "Parameter error, zero material!";
        return;
    }
    dbID id = tmpl->getID();
    dbID chapId = tmpl->chapterId();

    QSqlTableModel model;
    model.setTable("stockMaterial");
    QString templID = id.toString();
    model.setFilter( "matID=" + templID );
    model.select();

    QSqlRecord buffer = model.record();

    if( model.rowCount() > 0)
    {
        kDebug() << "Updating material chapter " << templID << endl;
        buffer = model.record(0);
        buffer.setValue( "chapterID", chapId.toString() );
        model.setRecord(0, buffer);
        model.submitAll();
    } else {
        kDebug() << "Could not update material chapter, not found with id " << templID;
    }
}
示例#10
0
void MemberDlg::deleteRecords()
{
    QItemSelectionModel *select_mode=view->selectionModel();

    QModelIndexList list = select_mode->selectedRows();
    qDebug()<<"list:"<<list.size();
    if(0 ==  list.count())
    {
        QMessageBox::information(NULL,tr("删除记录"),tr("对不起,请选择至少一条要删除的记录!"),
                                         QMessageBox::Yes);
        return;
    }
    else
    {
        int ret=QMessageBox::information(NULL,tr("删除记录"),tr("您确定要删除该记录?"),
                                         QMessageBox::Yes,QMessageBox::No);
        if(ret==QMessageBox::No)
            return;

       QSqlTableModel tableModel;
       tableModel.setTable("Account");
       for(int i=0; i<list.count();i++)
       {
           int MainID = model->data(model->index(list.at(i).row(),0)).toInt();
           tableModel.setFilter(QString("FamilyMember = %1").arg(MainID));
           tableModel.select();
           tableModel.removeRows(0,tableModel.rowCount()); //先删除Account与该成员关联的记录
       }

       model->removeRows(list.at(0).row(),list.count());
       model->submitAll();
       model->select();
    }
    emit updateFamilyMember();//通知其他窗体更新
}
void FormGestioneFerie::on_cbMatricola_currentIndexChanged(const QString &arg1)
{

    ui->cbCognome->setCurrentIndex(ui->cbMatricola->currentIndex());
    QSqlQuery query1(QString("SELECT nome FROM anagrafica where Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    query1.next();
    ui->lNome->setText( query1.value(0).toString() );

    QSqlTableModel *model = new QSqlTableModel(this, this->db);
    model->setTable("assenze");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->select();
    model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));

    model->sort(2,Qt::AscendingOrder);
      model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
      model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
      model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
      ui->tvPermessi->setModel(model);
      ui->tvPermessi->hideColumn(0);
      ui->tvPermessi->resizeColumnsToContents();
      ui->tvPermessi->resizeRowsToContents();
      ui->tvPermessi->selectRow(0);

}
示例#12
0
void MainWindow::setModel(QTableView *tableViewName, QString modelName, QString tableName, QStringList *tableFields, QString filter, int orderNum)
{
    QSqlTableModel *model;
    if (modelName == "modelEdit") {
        modelEdit = new QSqlTableModel;
        model = modelEdit;
    } else if (modelName == "modelChoose") {
        modelChoose = new QSqlTableModel;
        model = modelChoose;
    } else if (modelName == "modelQ") {
        modelQ = new QSqlTableModel;
        model = modelQ;
    } else if (modelName == "modelQE") {
        modelQE = new QSqlTableModel;
        model = modelQE;
    } else if (modelName == "modelNote") {
        modelNote = new QSqlTableModel;
        model = modelNote;
    } else if (modelName== "modelNotes") {
        modelNotes = new QSqlTableModel;
        model = modelNotes;
    } else {
        return;
    }

    model= new QSqlTableModel(this);
    model->setTable(tableName);
    model->setEditStrategy(QSqlTableModel::OnFieldChange);

    model->setSort(orderNum, Qt::DescendingOrder);

    int tableFieldsNum = tableFields->length();
    for (int i = 0; i < tableFieldsNum; i++) {
        model->setHeaderData(i, Qt::Horizontal, tableFields->at(i));
    }

    tableViewName->setModel(model);
    tableViewName->alternatingRowColors();
    tableViewName->horizontalHeader()->setStretchLastSection(true);

    model->setFilter(filter);
    model->select();
    tableViewName->reset();
    qDebug() << modelName << model << model->rowCount();

    if (modelName == "modelEdit") {
        modelEdit = model;
    } else if (modelName == "modelChoose") {
        modelChoose = model;
    } else if (modelName == "modelQ") {
        modelQ = model;
    } else if (modelName == "modelQE") {
        modelQE = model;
    } else if (modelName == "modelNote") {
        modelNote = model;
    } else if (modelName == "modelNotes") {
        modelNotes = model;
    } else return;
}
示例#13
0
void CDeleteAclTask::sendCMD(int groupId)
{
	QSqlTableModel model;
	QString filter1;
	SACL* psacl;
	char* pSendBuff;
	int len,len1;
	int ruleCount;

	model.setTable("aclrules");
	filter1 = QString("groupid=%1").arg(groupId);
	model.setFilter(filter1);
	model.select();

	ruleCount=model.rowCount();

	if (ruleCount==0)
	{
		//QMessageBox::information(this,"information", G2U(""));
		return;
	}

	psacl=new SACL[ruleCount];

	for (int i=0;i<model.rowCount();++i)
	{
		QSqlRecord record=model.record(i);
		psacl[i].cmdType=ACL_DELETE;             
		psacl[i].id=record.value("id").toInt();
	}

	len1=sizeof(SACL);
	len=ruleCount*len1;
	pSendBuff=new char[len];

	for (int i=0;i!=ruleCount;++i)
	{
		memcpy_s(pSendBuff+len1*i, len, (char*)&(psacl[i]), len1 );
	}

	boost::asio::io_service ios;
	CSocketClientSyn socketClientSyn(ios); 
	socketClientSyn.startConnection();
	socketClientSyn.sendData(pSendBuff,len);

	char* pRecvBuff=new char[len];
	socketClientSyn.recvData(pRecvBuff,len);
	socketClientSyn.closeConnection();

	for (int i=0;i!=ruleCount;++i)
	{
		memcpy_s(&psacl[i],len1,pRecvBuff+len1*i,len1);
		updateRules(psacl[i].id,psacl[i].cmdType);
	}
	delete [] psacl;
	delete [] pRecvBuff;
	delete [] pSendBuff;
}
示例#14
0
文件: ToolsFunc.cpp 项目: zzzzzsh/201
bool
ToolsFunc::setExerciseTable( const QString &user, QString &tableName )
{
    QSqlTableModel table;
    table.setTable( "instructor" );
    table.setFilter( QObject::tr( " user = '******'" ).arg( user ) );
    if( !table.select() || !table.rowCount() )
        return false;
    tableName = table.record(0).value( Enum::InstructorSection::Instructor_exercise_tables ).toString();
    return true;
}
示例#15
0
void simplePerson::setData(QString idx, QString tableName)
{
    QSqlTableModel model;
    model.setTable(tableName);
    model.setFilter(QString("id = %1").arg(idx));
    model.select();

    id = model.data(model.index(0,0)).toString();
    surname = model.data(model.index(0,1)).toString();
    name = model.data(model.index(0,2)).toString();
    patronimic = model.data(model.index(0,3)).toString();;
}
void FormGestioneFerie::on_pbAggiungiPermesso_clicked()
{
    for(QDate a=ui->dePermessiDal->date(); a.operator <=( ui->dePermessiAl->date());a= a.addDays(1) )
   {

    qDebug() << "Permesso per "+ui->cbMatricola->currentText()+" per il giorno "+a.toString("dd/MM/yyyy");


    QSqlQuery query;
    query.prepare("INSERT INTO assenze (ID, matricola, causa, data)" "VALUES (?, ?, ?, ?)");
   // query.addBindValue( ui->cbMatricola->currentText()+"_"+ui->dePermessiDal->date().toString("dd/MM/yyyy"));
    query.addBindValue( ui->cbMatricola->currentText()+"_"+a.toString("dd/MM/yyyy"));
    query.addBindValue( ui->cbMatricola->currentText());
    query.addBindValue( ui->cbTipoPermesso->currentText());
   // query.addBindValue( ui->dePermessiDal->date().toString("dd/MM/yyyy"));
    query.addBindValue( a.toString("dd/MM/yyyy"));
    if(query.exec())
    {
        QMessageBox msgBox;
        msgBox.setText("Inserzione nel database.");
        msgBox.setInformativeText(QString("Permesso per il giorno %1 inserito correttamente.").arg(a.toString("dd/MM/yyyy")));
        msgBox.setStandardButtons(QMessageBox::Ok );
        msgBox.setIcon(QMessageBox::Information);
        msgBox.exec();
    }
    else
    {
        QMessageBox msgBox;
        msgBox.setText("Inserzione nel database.");
        msgBox.setInformativeText(QString("Permesso per il giorno %1 NON inserito nel database. Probabilmente è gia stato inserito un permesso per lo stesso giorno.").arg(a.toString("dd/MM/yyyy")));
        msgBox.setStandardButtons(QMessageBox::Ok );
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();
    }

    QSqlTableModel *model = new QSqlTableModel(this, this->db);
    model->setTable("assenze");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->select();
    model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));

    model->sort(2,Qt::AscendingOrder);
      model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
      model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
      model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
      ui->tvPermessi->setModel(model);
      ui->tvPermessi->hideColumn(0);
      ui->tvPermessi->resizeColumnsToContents();
      ui->tvPermessi->resizeRowsToContents();
      ui->tvPermessi->selectRow(0);

  }
}
示例#17
0
QSqlTableModel* Dbconnect::select(QString table,QString filter)
{
    qDebug("selectDataSQL");
    QSqlTableModel *model = new QSqlTableModel;
    QString tbName = Db::tbPrefix;
    model->setTable(tbName.append(table));
    if("" != filter){
        model->setFilter(filter);
    }
    model->select();
    qDebug("-------%d",model->rowCount());
    return model;
}
示例#18
0
void EngineerExam::parseQuestions(QString filename) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(filename);
    if (!db.open()) {
	qCritical() << trUtf8("Nie można otworzyć bazy danych!");
    }

    QSqlTableModel question;
    question.setTable("Question");
    question.select();

    QSqlTableModel answers;
    answers.setTable("Answer");
    answers.select();

    QStringList qsl;

    int i = 0;
    while (question.canFetchMore()) {
	question.fetchMore();
	for (; i < question.rowCount(); ++i) {
	    qsl.clear();

	    quint32 id = question.record(i).value("Id").toUInt();
	    QString text = question.record(i).value("Text").toString();
	    Question q;
	    q.setId(id);
	    q.setQuestion(text);

	    answers.setFilter(QString("`id_Question` = %1").arg(id));
	    QString a1 = answers.record(0).value("Text").toString();
	    QString a2 = answers.record(1).value("Text").toString();
	    QString a3 = answers.record(2).value("Text").toString();
	    qsl << a1 << a2 << a3;

	    bool correct1 = answers.record(0).value("IsTrue").toBool();
	    bool correct2 = answers.record(1).value("IsTrue").toBool();
	    bool correct3 = answers.record(2).value("IsTrue").toBool();

	    if (correct1) {
		q.setCorrectAnswer(0);
	    } else if (correct2) {
		q.setCorrectAnswer(1);
	    } else if (correct3) {
		q.setCorrectAnswer(2);
	    }
	    q.setAnswers(qsl);
	    tmpList.append(q);
	}
    }
}
示例#19
0
void partner::setUpdate(QString idt)
{
	QSqlTableModel model;
	model.setTable("Partner");
	model.setFilter(QString("id = %1").arg(idt));
	model.select();
	id = model.data(model.index(0,0)).toInt();
	ui->nameEdit->setText(model.data(model.index(0,1)).toString());
	ui->surnameEdit->setText(model.data(model.index(0,2)).toString());
	ui->patronimicEdit->setText(model.data(model.index(0,3)).toString());
	ui->passportEdit->setText(model.data(model.index(0,4)).toString());
	ui->phoneEdit->setText(model.data(model.index(0,5)).toString());
	mode = updateMode;
}
示例#20
0
void Control::printNeighbor()
{
    QString whichID = ui->comboBox_5->currentText();
    QSqlTableModel* model = new QSqlTableModel(this);
    model->setTable("Distance");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setFilter("CellID1="+whichID+" and distance<=2 order by distance asc");
    model->setHeaderData(1,Qt::Horizontal,tr("邻居"));
    model->setHeaderData(2,Qt::Horizontal,tr("距离(千米)"));
    model->select();
    ui->tableView->setModel(model);
    ui->tableView->show();
    ui->tableView->setColumnHidden(model->fieldIndex("CellID1"),true);
}
示例#21
0
void FormPerson::loadLayout(QString tableName)
{
    // Recupero link al database
    QSqlDatabase db = QSqlDatabase::database("ConnectionToDB");
    // Creo un modello sche si riferirà alla tabella delle mail
    QSqlTableModel *model = new QSqlTableModel(this, db);

    // Imposto la tabella a cui si riferirà il modello
    model->setTable(tableName);
    // Imposto un filtro sulla persona a cui la tabella è collegata
    model->setFilter("id_person=" + QString::number(this->personId));
    model->select();

    // Per ciascuna riga della tabella...
    for (int i=0; i<model->rowCount(); i++)
    {
        QHBoxLayout *hbl = new QHBoxLayout();

        // Creo un nuovo oggetto QLineEdit
        QLineEdit *qlineedit = new QLineEdit();
        // Creo un pulsante per la successiva rimozione dell'entry nel database
        RemoveRowFromModel *button = new RemoveRowFromModel(i, model, tableName);
        // Collego il pulante alla funzione di refresh
        QObject::connect(button, SIGNAL(rowRemoved(QString)), this, SLOT(refreshLayout(QString)));

        // Creo un mapper
        QDataWidgetMapper *mapperEmailPerson = new QDataWidgetMapper();

        // Collego al mapper il modello della tabella
        mapperEmailPerson->setModel(model);
        // Aggiungo un mapping tra l'oggetto QLineEdit e il modello
        mapperEmailPerson->addMapping(qlineedit, 1);
        // Posiziono il mapper sull'indice opportuno
        mapperEmailPerson->setCurrentIndex(i);

        // Inserisco il mapper nella lista dei mapper per le email
        getQDataWidgetMapperList(tableName)->append(mapperEmailPerson);



        // qlineedit e button, li visualizzo sulla stessa riga (li inserisco in un layout orizzontale)
        hbl->addWidget(qlineedit);
        hbl->addWidget(button);
        // Inserisco il layout orizzontale nel layout delle mail
        getVerticalLayout(tableName)->addLayout(hbl);

        // Collego il pulsante ad uno slot, in modo che venga gestita la rimozione di una riga dal
        // modello
    }
}
QTreeWidgetItem *CollectionTreeWidget::addAlbum(QString artist, QString album, unsigned int albumId) {
    // Find id in database if we don't have it
    if (albumId == 0) {
         QSqlTableModel *model = service->collectionModel();

         // SQLite used two single quotes to escape a single quote! :)
         QString filter = "artist = '" + QString(artist).replace("'","''") + "' AND "
                          "album = '" + QString(album).replace("'","''") + "'";
         model->setFilter(filter);
         model->select();

         while (model->canFetchMore()) model->fetchMore();
         int total = model->rowCount();
         if (total > 0) {
            albumId = model->record(0).value(model->fieldIndex("id_album")).toInt();
         }
         else {
             qDebug("ERROR: no album found! -- " + model->filter().toUtf8());
             return NULL;
         }
    }

    // Looks for the artist
    QTreeWidgetItem *newAlbumNode; // The node with the album, whether it exists or not
    QTreeWidgetItem *artistItem;
    artistItem = addArtist(artist);

    // Look for album
    for (int i = 0; i < artistItem->childCount(); i++) {
        if (artistItem->child(i)->text(0) == album) {
            newAlbumNode = artistItem->child(i);
            return newAlbumNode;
        }
    }

    // Create our new album node and add it if it was not found
    newAlbumNode = new CollectionTreeWidgetItem(LevelAlbum, albumId, (QTreeWidget*)0);
    newAlbumNode->setText(0, album);
    newAlbumNode->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);

    // Set icon
    newAlbumNode->setIcon(0, IconFactory::fromTheme("media-cdrom"));

    artistItem->addChild(newAlbumNode);
    artistItem->sortChildren(0, Qt::AscendingOrder);

    return newAlbumNode;
}
示例#23
0
bool MaterialSaverDB::saveTemplate( StockMaterial *mat )
{
    bool res = true;

    // Transaktion ?

    QSqlTableModel model;
    model.setTable("stockMaterial");
    QString templID = QString::number( mat->getID() );
    model.setFilter( "matID=" + templID );
    model.select();

    QSqlRecord buffer = model.record();

    if( model.rowCount() > 0)
    {
        kDebug() << "Updating material " << mat->getID() << endl;

        // mach update
        buffer = model.record(0);
        fillMaterialBuffer( buffer, mat, false );
        model.setRecord(0, buffer);
        model.submitAll();
    }
    else
    {
        // insert
        kDebug() << "Creating new material database entry" << endl;

        fillMaterialBuffer( buffer, mat, true );
        model.insertRecord(-1, buffer);
        model.submitAll();

        /* Jetzt die neue Template-ID selecten */
        dbID id = KraftDB::self()->getLastInsertID();
        kDebug() << "New Database ID=" << id.toInt() << endl;

        if( id.isOk() ) {
            mat->setID( id.toInt() );
            templID = id.toString();
        } else {
            kDebug() << "ERROR: Kann AUTOINC nicht ermitteln" << endl;
            res = false;
        }
    }
    return res;
}
示例#24
0
// Leggo dal database le infomazioni "principali" relative alla persona this->personId
// e le rappresento tramite dei QLineEdit
void FormPerson::loadDb()
{
    // De-alloco eventuali model precedentemente creati
    QAbstractItemModel *modelToDelete =  this->mapperPersonData->model();
    delete(this->mapperPersonData);
    delete(modelToDelete);
    this->mapperPersonData = new QDataWidgetMapper();

    // Reference al database
    QSqlDatabase db = QSqlDatabase::database("ConnectionToDB");
    // Creazione di un modello ...
    QSqlTableModel *model = new QSqlTableModel(this, db);

    // ... che si riferisca alla tabella persons
    model->setTable("persons");
    // Imposto un filtro per lavorare su this->personId
    model->setFilter("id=" + QString::number(this->personId));
    // Eseguo la query
    model->select();


    // Associo al mapper il model
    this->mapperPersonData->setModel(model);

    // Eseguo il mapping dei campi del modello con i rispettivi campi di editing

    // Nome della Persona
    this->mapperPersonData->addMapping(this->ui->lineEdit_personName, 3);

    // Nickname della persona
    this->mapperPersonData->addMapping(this->ui->lineEdit_personNickname, 4);

    // Azienda in cui lavora la persona
    this->mapperPersonData->addMapping(this->ui->lineEdit_personComapny, 6 );

    // Titolo o ruolo svolto all'interno dell'azienda
    this->mapperPersonData->addMapping(this->ui->lineEdit_personTitle, 2);

    // Note associate alla persona
    this->mapperPersonData->addMapping(this->ui->textEdit_note, 7);

    this->mapperPersonData->toFirst();


    // Elementi da de-allocare:
    // model
}
示例#25
0
void Widget::on_withdraw_clicked()
{
    QSqlTableModel model;
    model.setTable("bankaccount");
    model.setFilter(tr("bankaccountnumber = '%1'").arg(name));
    model.select();
    int f = model.record(0).value("frozen").toInt();
    if(f==0)
    {
        withdraw withdrawinterface(name);
        withdrawinterface.exec();
    }
    else
    {
        QMessageBox::warning(NULL, "注意","您的账户已冻结!该操作已被禁止。");
    }

}
示例#26
0
void AdminDialog::initBorrowTableView()
{
    QSqlTableModel *model = new QSqlTableModel(this,Tool::getInstance()->getDb());
    model->setTable("borrow");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select(); //选取整个表的所有行
    model->setFilter("isreturn=0");
    model->removeColumn(model->columnCount()-1);
    model->removeColumn(model->columnCount()-1);
    model->setHeaderData(0,Qt::Horizontal,"借阅编号");
    model->setHeaderData(1,Qt::Horizontal,"图书编号");
    model->setHeaderData(2,Qt::Horizontal,"读者编号");
    model->setHeaderData(3,Qt::Horizontal,"剩余续借次数");
    model->setHeaderData(4,Qt::Horizontal,"借阅时间");
    model->setHeaderData(5,Qt::Horizontal,"应还时间");
    ui->tv3->setModel(model);
    ui->tv3->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
FormGestioneFerie::FormGestioneFerie(QSqlDatabase db, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormGestioneFerie)
{
    ui->setupUi(this);

    QDate oggi;
    ui->dePermessiDal->setDate(oggi.currentDate());
    ui->dePermessiAl->setDate(oggi.currentDate());

    this->db= db;



    QSqlQuery query(QString("SELECT Matricola,cognome FROM anagrafica"));
    while (query.next())
    {
     ui->cbMatricola->addItem(  query.value(0).toString() );
     ui->cbCognome->addItem(  query.value(1).toString() );
     ui->lNome->setText( query.value(2).toString() );
    }
    QSqlQuery query1(QString("SELECT nome FROM anagrafica where Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    query1.next();
    ui->lNome->setText( query1.value(0).toString() );



    QSqlTableModel *model = new QSqlTableModel(this, this->db);
    model->setTable("assenze");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->select();
    model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    model->sort(2,Qt::AscendingOrder);
    model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
    model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
    model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
    ui->tvPermessi->setModel(model);
    ui->tvPermessi->hideColumn(0);
    ui->tvPermessi->resizeColumnsToContents();
    ui->tvPermessi->resizeRowsToContents();
    ui->tvPermessi->selectRow(0);


}
示例#28
0
void Control::findCellInfo()
{
    if(!checkDurationValid())
    {
        QMessageBox::warning(this,"警告","请选择正确的时间段",QMessageBox::Yes);
        return;
    }
    if(ui->lineEdit->text().isEmpty())
    {
        QMessageBox::warning(this,"警告","请输入拥塞门限(0到1的小数)",QMessageBox::Yes);
        return;
    }
    double rate= ui->lineEdit->text().toDouble();
    QSqlQuery query;
    query.exec("exec countCongs");
    QDateTime start = ui->startDateTimeEdit->dateTime();
    QDateTime end = ui->endDateTimeEdit->dateTime();

    int year1 = start.date().year() % 10 * 10000;
    int month1 = start.date().month() * 100;
    int day1 = start.date().day();
    int hour1 = start.time().hour();
    int year2 = end.date().year() % 10 * 10000;
    int month2 = end.date().month() * 100;
    int day2 = end.date().day();
    int hour2 = end.time().hour();

    query.exec(QString("exec finder2 %1,%2,%3,%4,%5").arg(rate).arg(year1 + month1 + day1).arg(hour1)
               .arg(year2 + month2 + day2).arg(hour2));//finder2只列rate超过门限的部分数据

    QSqlTableModel* model = new QSqlTableModel(this);
    model->setTable("H_result");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setFilter("H_rate>"+QString::number(rate) +" order by CellID,bdate,btime");
    model->setHeaderData(0,Qt::Horizontal,tr("日期"));
    model->setHeaderData(1,Qt::Horizontal,tr("小时"));
    model->setHeaderData(2,Qt::Horizontal,tr("小区ID"));
    model->setHeaderData(3,Qt::Horizontal,tr("小时级话务量"));
    model->setHeaderData(4,Qt::Horizontal,tr("小时级拥塞率"));
    model->setHeaderData(5,Qt::Horizontal,tr("小时级半速率话务量比例"));
    model->select();
    ui->tableView_2->setModel(model);
    ui->tableView_2->show();
}
QTreeWidgetItem *CollectionTreeWidget::addArtist(QString artist, unsigned int id) {
    if (id == 0) {
        QSqlTableModel *model = service->artistModel();

        // SQLite uses two single quotes to escape a single quote! :)
        QString filter = "name = '" + QString(artist).replace("'","''") + "'";
        model->setFilter(filter);
        model->select();

        while (model->canFetchMore()) model->fetchMore();
        int total = model->rowCount();
        if (total > 0) {
            id = model->record(0).value(model->fieldIndex("id")).toInt();
        }
        else {
            qDebug("ERROR: no artist found! -- " + model->filter().toUtf8());
            return NULL;
        }
    }

    QList<QTreeWidgetItem*> artistList = findItems(artist, Qt::MatchExactly, 0);
    if (artistList.isEmpty()) {
        CollectionTreeWidgetItem *item = new CollectionTreeWidgetItem(LevelArtist, id, (QTreeWidget*)0);
        item->setText(0, artist);
        item->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);

        // Set font to bold
        QFont font = item->font(0);
        font.setBold(true);
        item->setFont(0, font);

        // Set icon
        item->setIcon(0, IconFactory::fromTheme("folder"));

        // Insert item
        insertTopLevelItem(0, item);
        sortItems(0, Qt::AscendingOrder);

        return item;
    }
    else {
        return artistList.first();
    }
}
示例#30
0
void DialogVibSotr::setModel(ProfimaxRelationalModel* modd) {

	model = modd;

	// Page Профсоюз
	QSqlTableModel* relModel = model->relationModel(model->fieldIndex("member_id"));
	relModel->setFilter("not (member_id=1 or member_id=5)");
	comboBoxMember->setModel(relModel);
	comboBoxMember->setModelColumn(relModel->fieldIndex("name"));

	mapper->setModel(model);
	mapper->setItemDelegate(new QSqlRelationalDelegate(this));

	mapper->addMapping(lineEditLastName, model->fieldIndex("lastname"));
	mapper->addMapping(lineEditFirstName, model->fieldIndex("firstname"));
	mapper->addMapping(lineEditMidName, model->fieldIndex("midname"));
	mapper->addMapping(lineEditTabNum, model->fieldIndex("tabnum"));
	mapper->addMapping(dateEditDate, model->fieldIndex("date_in"));
	mapper->addMapping(comboBoxMember, model->fieldIndex("member_id"));

}