Ejemplo n.º 1
2
        void FenPrincipale::submitChangement()
        {
            QSqlTableModel *model = qobject_cast<QSqlTableModel *>(tabless->model());
            model->database().transaction();
               if (model->submitAll()) {
                   model->database().commit();
               } else {
                   model->database().rollback();
                   QMessageBox::warning(this, tr("Cached Table"),
                                        tr("The database reported an error: %1")
                                        .arg(model->lastError().text()));
               }

        }
Ejemplo n.º 2
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);
}
Ejemplo n.º 3
1
void Database::deactivateUser(QString &userName)
{
    QSqlTableModel model;
    model.setTable("user");
    model.select();

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            record.setValue("isActive", false);
            model.setRecord(i, record);
            model.submitAll();
            break;
        }
    }
}
Ejemplo n.º 4
1
void mainWindow::editGame()
{
    if(ui->tableGames->currentIndex().isValid())
    {
        QString console = ui->tableGames->model()->data(ui->tableGames->model()->index(ui->tableGames->currentIndex().row(), 0)).toString();
        QString title = ui->tableGames->model()->data(ui->tableGames->model()->index(ui->tableGames->currentIndex().row(), 1)).toString();
        QString annee = ui->tableGames->model()->data(ui->tableGames->model()->index(ui->tableGames->currentIndex().row(), 2)).toString();
        QString devs = ui->tableGames->model()->data(ui->tableGames->model()->index(ui->tableGames->currentIndex().row(), 3)).toString();

        QSqlTableModel* m = new QSqlTableModel();
        m->setTable("Consoles");
        m->removeColumn(0);
        m->select();

        QStringList list;

        for(int i = 0; i < m->rowCount(); i++)
        {
            list.append(m->record(i).value(0).toString());
        }
        list.removeDuplicates();

        editDialog* d = new editDialog(list, this, console, title, annee, devs);

        if(d->exec() == QDialog::Accepted)
        {
            QSqlQuery q;

            QString query = "UPDATE Games "
                    "SET console='" + d->console() + "', "
                    "titre='" + d->titre() + "', "
                    "annee='" + d->annee() + "', "
                    "devs='" + d->devs() + "' "
                    "WHERE console='" + console +"' AND titre='" + title + "' AND annee='"+ annee +
                    "' AND devs='" + devs + "';";

            q.exec(query);

            m_model->select();
        }
    }
}
Ejemplo n.º 5
0
//------------------Above Date--------------------------
void Liveinfo::UpdateRoom(int RoomNum,int change)
{
	QSqlTableModel * updateroom = new QSqlTableModel;		//修改已入住的房间
	updateroom->setTable("Room");
	updateroom->select();	
	for(int i = 0;i < updateroom->rowCount(); ++i)
	{		
		QSqlRecord Roomrecord = updateroom->record(i);
		int check_room = Roomrecord.value("Num").toInt();
		if( check_room == RoomNum )
		{
			Roomrecord.setValue("Live",change);
			updateroom->setRecord(i, Roomrecord);
		}
	}		
	updateroom->submitAll();
}
Ejemplo n.º 6
0
void QSqlTableModel_snippets()
{
//! [24]
    QSqlTableModel *model = new QSqlTableModel(parentObject, database);
    model->setTable("employee");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    model->setHeaderData(0, Qt::Horizontal, tr("Name"));
    model->setHeaderData(1, Qt::Horizontal, tr("Salary"));

    QTableView *view = new QTableView;
    view->setModel(model);
    view->hideColumn(0); // don't show the ID
    view->show();
//! [24]

    {
//! [25]
    QSqlTableModel model;
    model.setTable("employee");
    QString name = model.record(4).value("name").toString();
//! [25]
    }
}
Ejemplo n.º 7
0
void Database::saveXP(QString &userName, int xp)
{
    QSqlTableModel model;
    model.setTable("user");
    model.select();

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            record.setValue("experiencePoints", xp);
            model.setRecord(i, record);
            model.submitAll();
            break;
        }
    }
}
Ejemplo n.º 8
0
void Database::saveLevel(QString &userName, int level)
{
    QSqlTableModel model;
    model.setTable("user");
    model.select();

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            record.setValue("level", level);
            model.setRecord(i, record);
            model.submitAll();
            break;
        }
    }
}
Ejemplo n.º 9
0
void Browser::showTable(const QString &t)
{
    QSqlTableModel *model = new QSqlTableModel(table, connectionWidget->currentDatabase());
    model->setEditStrategy(QSqlTableModel::OnRowChange);
    model->setTable(t);
    model->select();
    if (model->lastError().type() != QSqlError::NoError)
        emit statusMessage(model->lastError().text());
    table->setModel(model);
    table->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed);

    connect(table->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            this, SLOT(currentChanged()));
    updateActions();
}
Ejemplo n.º 10
0
void Database::saveUser(QString &userName, User user)
{
    QSqlTableModel model;
    model.setTable("user");
    model.select();

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            record.setValue("experiencePoints", user.experiencePoints);
            record.setValue("isActive", user.isActive);
            record.setValue("level", user.level);
            model.setRecord(i, record);
            model.submitAll();
            break;
        }
    }
}
Ejemplo n.º 11
0
bool ChangePassword::on_pushButton_clicked()
{

    if (ui->new_2->text()!= ui->new_3->text())
    {
        QMessageBox::information(this, tr("警告!"),tr("两次输入的密码不一致,请重新输入!"));
        ui->new_2->clear();
        ui->new_3->clear();
        return false;
    }
    root.open();

    QSqlTableModel *user = new QSqlTableModel(this,root);
    user->setTable("user");
    user->setFilter(tr("user='******' and password = '******'").arg(username,ui->old->text()));
    user->select();

    if (user->rowCount() <= 0)
    {
        QMessageBox::information(this, tr("警告!"),tr("密码输入错误,请重新输入!"));
        root.close();

        return false;
    }
    else
    {
        user->setData(user->index(0,1),ui->new_2->text());
        user->submitAll();
        root.close();
        QMessageBox::information(this, tr(" 修改成功!"),tr("密码修改成功!!"));
        close();
        return true;

    }
    root.close();
}
Ejemplo n.º 12
0
void MySqlRelationDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if (!index.isValid())
        return;

    QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel *>(model);
    QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0;
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    if (!sqlModel || !childModel || !combo) {
        if (HandbookDialog::m_record.fieldName(index.column()).contains("IS_", Qt::CaseSensitive))
        {
            QCheckBox * checkBox = qobject_cast<QCheckBox *>(editor);
            sqlModel->setData(index, checkBox->isChecked(), Qt::DisplayRole);
            sqlModel->setData(index, checkBox->isChecked(), Qt::EditRole);
            return;
        }
        else if (HandbookDialog::m_record.fieldName(index.column()).contains("DATE_", Qt::CaseSensitive))
        {
            QDateEdit * dateEdit = qobject_cast<QDateEdit *>(editor);
            sqlModel->setData(index, dateEdit->date().toString("yyyy-MM-dd"), Qt::DisplayRole);
            sqlModel->setData(index, dateEdit->date().toString("yyyy-MM-dd"), Qt::EditRole);
            return;
        }
        else
        {
            QItemDelegate::setModelData(editor, model, index);
            return;
        }
    }

    int currentItem = combo->currentIndex();
    int childColIndex = childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn());
    int childEditIndex = childModel->fieldIndex(sqlModel->relation(index.column()).indexColumn());
    sqlModel->setData(index,
            childModel->data(childModel->index(currentItem, childColIndex), Qt::DisplayRole),
            Qt::DisplayRole);
    sqlModel->setData(index,
            childModel->data(childModel->index(currentItem, childEditIndex), Qt::EditRole),
            Qt::EditRole);
}
Ejemplo n.º 13
0
void mainWindow::setupComboBox()
{
    QSqlTableModel* m = new QSqlTableModel();
    m->setTable("Consoles");
    m->removeColumn(0);
    m->select();

    QStringList list;

    for(int i = 0; i < m->rowCount(); i++)
    {
        list.append(m->record(i).value(0).toString());
    }
    list.removeDuplicates();
    list.sort();
    ui->comboConsole->clear();
    ui->comboConsole->addItems(list);
}
Ejemplo n.º 14
0
Widget::Widget(QString n, QString p, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    setFixedSize(470,230);
    setWindowTitle("您的银行账户");
    name = n;
    pwd = p;
    QSqlTableModel model;
    model.setTable("bankaccount");
    model.setFilter(tr("bankaccountnumber = '%1'").arg(name));
    model.select();
    QString bn = model.record(0).value("bankname").toString();
    QString ln = model.record(0).value("lastname").toString();
    QString fn = model.record(0).value("firstname").toString();
    QString ban = model.record(0).value("bankaccountnumber").toString();
    ui->bankname->setText(tr("%1").arg(bn));
    ui->name->setText(tr("%1%2").arg(ln).arg(fn));
    ui->bankan->setText(tr("%1").arg(ban));


}
Ejemplo n.º 15
0
void SelectLiftDlg::on_pushBtnSel_clicked()
{
    int curRow = ui->tableView->currentIndex().row();
    if(curRow<0)
    {
        QMessageBox::warning(this,"警告","请先选择电梯!",QMessageBox::Yes);
        return;
    }
    QSqlTableModel *modelTable = new QSqlTableModel(this);
    modelTable->setTable("tableLift");
    modelTable->select();

    for(int i=0;i<modelTable->columnCount();i++)
    {
        QModelIndex index = modelTable->index(curRow,i);
        arrValues.push_back(modelTable->data(index).toString());
    }

    accept();
}
Ejemplo n.º 16
0
void loginFrame::deleteUserInfo()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("Registry.db");
    if(!db.open())
        return;
    QSqlTableModel *model = new QSqlTableModel();
    model->setTable("userlist");
    model->select();
    //删除相应行
    model->removeRow(ui->comboBox->currentIndex());
    model->submitAll();
    //修正combobox的显示
    RegistyShowID.removeAt(ui->comboBox->currentIndex());
    ui->comboBox->removeItem(ui->comboBox->currentIndex());
    ui->comboBox->setCurrentIndex(0);
    for(int i=0;i<model->rowCount();i++)
    {
        ui->comboBox->setIconSize(QSize(20,20));
        ui->comboBox->setItemIcon(i,QIcon(":/images/head.png"));
        ui->comboBox->setItemText(i,RegistyShowID.at(i).id);
    }
}
Ejemplo n.º 17
0
QString CacheDatabase::getField(const QString &what, const QString &where, const QString &value)
{
    // If same return
    if(what == where)
        return QString::null;
    // Create model
    QSqlTableModel* model = new QSqlTableModel;
    // Set table
    model->setTable(CacheTableName);
    // Edit stategy
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    // Set filter
    model->setFilter(QString("%1='%2'").arg(where, value));
    // Run selection
    model->select();
    // Get record
    QSqlRecord record = model->record(0);
    // If not empty
    if(!record.isEmpty())
        // Get value
        return record.value(record.indexOf(what)).toString();
    // Return result
    return QString::null;
}
Ejemplo n.º 18
0
void Liveinfo::SubmitButton()
{
//	bool a,b,c;
	if(NameEdit->text().isEmpty() || ContactEdit->text().isEmpty() || IDEdit->text().isEmpty() || 
                DaysEdit->text().isEmpty() || DespoitEdit->text().isEmpty())
	{
                QMessageBox::critical(0,QObject::tr("Error!"),QObject::tr("Please Fill them all!"),QMessageBox::Cancel);
	}
	else
	{
		QString Ename = NameEdit->text();
		QString Econtact = ContactEdit->text();
		QString EID = IDEdit->text();
		QString Edays = DaysEdit->text();
		QString Edeposit = DespoitEdit->text();
		QDate cudate = QDate::currentDate();
		cudate = cudate.addDays(Edays.toInt());
		Eetime = cudate.toString("yyyy-MM-dd");
		
		QSqlTableModel *insertGuest = new QSqlTableModel;		//修改Guest中的记录
		insertGuest->setTable("Guest");
	    insertGuest->select();			// 只要指定Row=0即可插入新行
	    int row = 0;
	    insertGuest->insertRows(row,1);
	    insertGuest->setData(insertGuest->index(row, 0), QVariant(Ename));
	    insertGuest->setData(insertGuest->index(row, 1), QVariant(EID));
	    insertGuest->setData(insertGuest->index(row, 2), QVariant(Econtact));
	    insertGuest->setData(insertGuest->index(row, 3), QVariant(RoomNum));
	//  a = insertGuest->submit();
	  	insertGuest->submit();
	    
	    QSqlTableModel *insertRecord = new QSqlTableModel;		//修改Record中的记录
	    insertRecord->setTable("Record");
	    insertRecord->select();
	    insertRecord->insertRows(row,1);
	    insertRecord->setData(insertRecord->index(row,0),QVariant(Ename));
	    insertRecord->setData(insertRecord->index(row,1),QVariant(RoomNum));
	    insertRecord->setData(insertRecord->index(row,2),QVariant(Edays));
	    insertRecord->setData(insertRecord->index(row,3),QVariant(Edeposit));
	    insertRecord->setData(insertRecord->index(row,4),QVariant(Estime));
	    insertRecord->setData(insertRecord->index(row,5),QVariant(Eetime));
	//  b = insertRecord->submit();
		insertRecord->submit();
		
		UpdateRoom(RoomNum,1);    //修改已入住的房间
	
	//	if(a && b && c)
	//	{	
			QMessageBox msgBox;
			msgBox.setText("Succeed to live in! Welcome");
			msgBox.exec();
	//	}	
		 QDialog::accept();
	 }
}
Ejemplo n.º 19
0
int IDResource::getSingleIdRes(QString& idType)
{
	QSqlTableModel model;
	model.setTable(idType);
	QString filter1="";
	int minNum,maxNum;

	if (idType==tr("ACLID"))
	{
		filter1=QString("ID>=%1 and ID<=%2").arg(g_minACLID).arg(g_maxACLID);
		minNum=g_minACLID;
		maxNum=g_maxACLID;
	}
	else if (idType==tr("XACLID"))
	{
		filter1=QString("ID>=%1 and ID<=%2").arg(g_minXACLID).arg(g_maxXACLID);
		minNum=g_minXACLID;
		maxNum=g_maxXACLID;
	}
	else if (idType==tr("PLID"))
	{
		filter1=QString("ID>=%1 and ID<=%2").arg(g_minPLID).arg(g_maxPLID);
		minNum=g_minPLID;
		maxNum=g_maxPLID;
	}
	
	model.setFilter(filter1);
	model.setSort( 0, Qt::AscendingOrder);
	model.select();
		
	QSet<int>idSet;
	
	for(int j=0;j<model.rowCount();++j)
	{
		QSqlRecord record=model.record(j);
		idSet<<record.value("id").toInt();
	}
	
	QQueue<int>queueId;
	
	for(int j=minNum;j!=maxNum+1;++j)
	{
		if(!idSet.contains(j))
		{
			queueId.enqueue(j);
		}
	}
	
	idSet.clear();
	
	if(queueId.count()<=0)
	{
		QMessageBox::information(this, tr("information"), tr("无可用ID资源"));
	}

	while(true)
	{
		int resId=queueId.dequeue();
	    if(!idConflict(resId,idType))
			return resId;
	}
	
	return 0;
}
Ejemplo n.º 20
0
EmployeeForm::EmployeeForm(int id, QWidget *parent)
    : QDialog(parent)
{
    nameEdit = new QLineEdit;

    nameLabel = new QLabel(tr("Na&me:"));
    nameLabel->setBuddy(nameEdit);

    departmentComboBox = new QComboBox;

    departmentLabel = new QLabel(tr("Depar&tment:"));
    departmentLabel->setBuddy(departmentComboBox);

    extensionLineEdit = new QLineEdit;
	extensionLineEdit->setValidator(
								new QIntValidator(0, 99999, this));

    extensionLabel = new QLabel(tr("E&xtension:"));
    extensionLabel->setBuddy(extensionLineEdit);

    emailEdit = new QLineEdit;

    emailLabel = new QLabel(tr("&Email:"));
    emailLabel->setBuddy(emailEdit);

    startDateEdit = new QDateEdit;
    startDateEdit->setCalendarPopup(true);
    QDate today = QDate::currentDate();
	startDateEdit->setDateRange(
			today.addDays(-90), today.addDays(90));

    startDateLabel = new QLabel(tr("&Start Date:"));
    startDateLabel->setBuddy(startDateEdit);

    firstButton = new QPushButton(tr("<< &First"));
    previousButton = new QPushButton(tr("< &Previous"));
    nextButton = new QPushButton(tr("&Next >"));
    lastButton = new QPushButton(tr("&Last >>"));

    addButton = new QPushButton(tr("&Add"));
    deleteButton = new QPushButton(tr("&Delete"));
    closeButton = new QPushButton(tr("&Close"));

    buttonBox = new QDialogButtonBox;
    buttonBox->addButton(addButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(deleteButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(closeButton, QDialogButtonBox::AcceptRole);

    tableModel = new QSqlRelationalTableModel(this);
    tableModel->setTable("employee");
    tableModel->setRelation(Employee_DepartmentId,
                            QSqlRelation("department", "id", "name"));
    tableModel->setSort(Employee_Name, Qt::AscendingOrder);
    tableModel->select();

    QSqlTableModel *relationModel =
            tableModel->relationModel(Employee_DepartmentId);
    departmentComboBox->setModel(relationModel);
    departmentComboBox->setModelColumn(
            relationModel->fieldIndex("name"));

    mapper = new QDataWidgetMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
    mapper->setModel(tableModel);
    mapper->setItemDelegate(new QSqlRelationalDelegate(this));
    mapper->addMapping(nameEdit, Employee_Name);
    mapper->addMapping(departmentComboBox, Employee_DepartmentId);
    mapper->addMapping(extensionLineEdit, Employee_Extension);
    mapper->addMapping(emailEdit, Employee_Email);
    mapper->addMapping(startDateEdit, Employee_StartDate);

	if (id != -1)
	{
		for (int row = 0; row < tableModel->rowCount(); ++row)
		{
            QSqlRecord record = tableModel->record(row);
            if (record.value(Employee_Id).toInt() == id) {
                mapper->setCurrentIndex(row);
                break;
            }
        }
	 }
	else
	{
        mapper->toFirst();
    }

    connect(firstButton, SIGNAL(clicked()), mapper, SLOT(toFirst()));
    connect(previousButton, SIGNAL(clicked()),
            mapper, SLOT(toPrevious()));
    connect(nextButton, SIGNAL(clicked()), mapper, SLOT(toNext()));
    connect(lastButton, SIGNAL(clicked()), mapper, SLOT(toLast()));

	connect(addButton, SIGNAL(clicked()),
			this, SLOT(addEmployee()));
    connect(deleteButton, SIGNAL(clicked()),
            this, SLOT(deleteEmployee()));
    connect(closeButton, SIGNAL(clicked()), this, SLOT(accept()));

    QHBoxLayout *topButtonLayout = new QHBoxLayout;
    topButtonLayout->setContentsMargins(20, 0, 20, 5);
    topButtonLayout->addStretch();
    topButtonLayout->addWidget(firstButton);
    topButtonLayout->addWidget(previousButton);
    topButtonLayout->addWidget(nextButton);
    topButtonLayout->addWidget(lastButton);
    topButtonLayout->addStretch();

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addLayout(topButtonLayout, 0, 0, 1, 3);
    mainLayout->addWidget(nameLabel, 1, 0);
    mainLayout->addWidget(nameEdit, 1, 1, 1, 2);
    mainLayout->addWidget(departmentLabel, 2, 0);
    mainLayout->addWidget(departmentComboBox, 2, 1, 1, 2);
    mainLayout->addWidget(extensionLabel, 3, 0);
    mainLayout->addWidget(extensionLineEdit, 3, 1);
    mainLayout->addWidget(emailLabel, 4, 0);
    mainLayout->addWidget(emailEdit, 4, 1, 1, 2);
    mainLayout->addWidget(startDateLabel, 5, 0);
    mainLayout->addWidget(startDateEdit, 5, 1);
    mainLayout->addWidget(buttonBox, 7, 0, 1, 3);
    mainLayout->setRowMinimumHeight(6, 10);
    mainLayout->setRowStretch(6, 1);
    mainLayout->setColumnStretch(2, 1);
    setLayout(mainLayout);

    if (id == -1) {
        nextButton->setFocus();
    } else {
        nameEdit->setFocus();
    }

    setWindowTitle(tr("Edit Employees"));
}
Ejemplo n.º 21
0
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;
}
Ejemplo n.º 22
0
void EditColumnFormatsDialog::editItem(EditorType type) {
    if (type == EditItem && selectionIsEmpty()) {
        selectionIsEmptyWarning();
        return;
    }
    QModelIndex index = listView->currentIndex();
    QSqlRecord record = model_->record(index.row());
    int id = record.value(ColumnFormat_Id).toInt();
    QSqlQuery query(QString("SELECT Intervals.Name FROM ColumnFormats "
                            "JOIN ColumnFormatInterval USING (ColumnFormatID) "
                            "JOIN Intervals USING (IntervalID) "
                            "WHERE ColumnFormatInterval.ColumnFormatID = %1 "
                            "ORDER BY SortOrder").arg(id));
    if (!query.isActive()) {
        QMessageBox::warning(this, tr("Database Error"),
                             query.lastError().text());
        return;
    }
    QList<EpCore::Interval> intervals;
    while (query.next()) {
        QString value = query.value(0).toString();
        intervals.append(value);
    }
    EditColumnFormatDialog d(type, this);
    if (type == EditItem) {
        QString columnFormatName = record.value(ColumnFormat_Name).toString();
        EpCore::ColumnFormat columnFormat(columnFormatName, intervals);
        d.setColumnFormat(columnFormat);
    }
    else if (type == NewItem) {
        EpCore::ColumnFormat columnFormat;
        d.setColumnFormat(columnFormat);
    }
    if (d.exec() == QDialog::Accepted) {
        EpCore::ColumnFormat columnFormat = d.columnFormat();
        if (type == EditItem)
            removeIntervals();
        int row = index.row();
        if (type == NewItem)
            model_->insertRows(row, 1);
        model_->setData(model_->index(row, ColumnFormat_Name), 
                        columnFormat.name());
        model_->submitAll();
        model_->select();
        QSqlTableModel updateModel;
        updateModel.setTable("ColumnFormats");
        updateModel.setFilter(QString("Name = '%1'").arg(columnFormat.name()));
        updateModel.select();
        int newId = 0;
        QString newName;
        if (updateModel.rowCount() >= 1) {
            QSqlRecord record = updateModel.record(0);
            newId = record.value(0).toInt();
            newName = record.value(1).toString();
        }
        QList<EpCore::Interval> intervals = columnFormat.intervals();
        QListIterator<EpCore::Interval> iter(intervals);
        int i = 0;
        QSqlDatabase::database().transaction();
        while (iter.hasNext()) {
            QSqlQuery lookup(QString("SELECT IntervalID FROM Intervals "
                                     "WHERE Name = '%1'")
                             .arg(iter.next().name()));
            int lookupId;
            while (lookup.next()) {
                lookupId = lookup.value(0).toInt();
                QSqlQuery insertQuery(QString("INSERT INTO "
                                              "ColumnFormatInterval "
                                              "(ColumnFormatID, "
                                              "IntervalID, SortOrder) "
                                              "VALUES (%1, %2, %3)")
                                      .arg(newId).arg(lookupId).arg(i++));
            }
        }
        QSqlDatabase::database().commit();
    }
}
Ejemplo n.º 23
0
QgsBookmarks::QgsBookmarks( QWidget *parent ) : QDockWidget( parent )
{
    setupUi( this );
    restorePosition();

    QToolButton* btnImpExp = new QToolButton;
    btnImpExp->setAutoRaise( true );
    btnImpExp->setToolTip( tr( "Import/Export Bookmarks" ) );
    btnImpExp->setIcon( QgsApplication::getThemeIcon( "/mActionSharing.svg" ) );
    btnImpExp->setPopupMode( QToolButton::InstantPopup );

    QMenu *share = new QMenu( this );
    QAction *btnExport = share->addAction( tr( "&Export" ) );
    QAction *btnImport = share->addAction( tr( "&Import" ) );
    btnExport->setIcon( QgsApplication::getThemeIcon( "/mActionSharingExport.svg" ) );
    btnImport->setIcon( QgsApplication::getThemeIcon( "/mActionSharingImport.svg" ) );
    connect( btnExport, SIGNAL( triggered() ), this, SLOT( exportToXML() ) );
    connect( btnImport, SIGNAL( triggered() ), this, SLOT( importFromXML() ) );
    btnImpExp->setMenu( share );

    connect( actionAdd, SIGNAL( triggered() ), this, SLOT( addClicked() ) );
    connect( actionDelete, SIGNAL( triggered() ), this, SLOT( deleteClicked() ) );
    connect( actionZoomTo, SIGNAL( triggered() ), this, SLOT( zoomToBookmark() ) );

    mBookmarkToolbar->addWidget( btnImpExp );
    mBookmarkToolbar->addAction( actionHelp );

    // open the database
    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE", "bookmarks" );
    db.setDatabaseName( QgsApplication::qgisUserDbFilePath() );
    if ( !db.open() )
    {
        QMessageBox::warning( this, tr( "Error" ),
                              tr( "Unable to open bookmarks database.\nDatabase: %1\nDriver: %2\nDatabase: %3" )
                              .arg( QgsApplication::qgisUserDbFilePath() )
                              .arg( db.lastError().driverText() )
                              .arg( db.lastError().databaseText() )
                            );
        deleteLater();
        return;
    }

    QSqlTableModel *model = new QSqlTableModel( this, db );
    model->setTable( "tbl_bookmarks" );
    model->setSort( 0, Qt::AscendingOrder );
    model->setEditStrategy( QSqlTableModel::OnFieldChange );
    model->select();

    // set better headers then column names from table
    model->setHeaderData( 0, Qt::Horizontal, tr( "ID" ) );
    model->setHeaderData( 1, Qt::Horizontal, tr( "Name" ) );
    model->setHeaderData( 2, Qt::Horizontal, tr( "Project" ) );
    model->setHeaderData( 3, Qt::Horizontal, tr( "xMin" ) );
    model->setHeaderData( 4, Qt::Horizontal, tr( "yMin" ) );
    model->setHeaderData( 5, Qt::Horizontal, tr( "xMax" ) );
    model->setHeaderData( 6, Qt::Horizontal, tr( "yMax" ) );
    model->setHeaderData( 7, Qt::Horizontal, tr( "SRID" ) );

    lstBookmarks->setModel( model );

    QSettings settings;
    lstBookmarks->header()->restoreState( settings.value( "/Windows/Bookmarks/headerstate" ).toByteArray() );

#ifndef QGISDEBUG
    lstBookmarks->setColumnHidden( 0, true );
#endif
}
Ejemplo n.º 24
0
EditProtocolDialog::EditProtocolDialog(AbstractEditItemsDialog::EditorType type,
                                       QSqlRelationalTableModel* model,
                                       int row,
                                       QWidget *parent)
    : QDialog(parent){
    setupUi(this);
    QString title = type == AbstractEditItemsDialog::NewItem
        ? tr("New") : tr("Edit");
    title = tr("%1 Protocol").arg(title);
    setWindowTitle(title);

    mapper_ = new QDataWidgetMapper(this);
    mapper_->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
    mapper_->setModel(model);
    mapper_->setItemDelegate(new QSqlRelationalDelegate(this));
    mapper_->addMapping(nameLineEdit, EditProtocolsDialog::Protocol_Name);
    QSqlTableModel* senseChannelLabelModel =
        model->relationModel(EditProtocolsDialog::Protocol_SenseChannelLabelID);
    senseChannelLabelComboBox->setModel(senseChannelLabelModel);
    senseChannelLabelComboBox->setModelColumn(senseChannelLabelModel->
                                              fieldIndex("Name"));
    mapper_->addMapping(senseChannelLabelComboBox, 
                        EditProtocolsDialog::Protocol_SenseChannelLabelID);
    QSqlTableModel* columnFormatModel =
        model->relationModel(EditProtocolsDialog::Protocol_ColumnFormatID);
    columnFormatComboBox->setModel(columnFormatModel);
    columnFormatComboBox->setModelColumn(columnFormatModel->fieldIndex("Name"));
    mapper_->addMapping(columnFormatComboBox,
                        EditProtocolsDialog::Protocol_ColumnFormatID);
    QSqlTableModel* windowSettingModel =
        model->relationModel(EditProtocolsDialog::Protocol_WindowSettingID);
    windowSettingComboBox->setModel(windowSettingModel);
    windowSettingComboBox->setModelColumn(windowSettingModel->fieldIndex("Name"));
    mapper_->addMapping(windowSettingComboBox,
                        EditProtocolsDialog::Protocol_WindowSettingID);
    QSqlTableModel* macroCategoryModel =
        model->relationModel(EditProtocolsDialog::Protocol_MacroCategoryID);
    macroCategoryComboBox->setModel(macroCategoryModel);
    macroCategoryComboBox->setModelColumn(macroCategoryModel->fieldIndex("Name"));
    mapper_->addMapping(macroCategoryComboBox,
                        EditProtocolsDialog::Protocol_MacroCategoryID);
    QSqlTableModel* updateReviewModel = 
        model->relationModel(EditProtocolsDialog::Protocol_UpdateReviewWindowID);
    updateReviewComboBox->setModel(updateReviewModel);
    updateReviewComboBox->setModelColumn(updateReviewModel->fieldIndex("Name"));
    mapper_->addMapping(updateReviewComboBox, 
                        EditProtocolsDialog::Protocol_UpdateReviewWindowID);
    QSqlTableModel* focalPointModel = 
        model->relationModel(EditProtocolsDialog::Protocol_FocalPointID);
    focalPointComboBox->setModel(focalPointModel);
    focalPointComboBox->setModelColumn(focalPointModel->fieldIndex("Name"));
    mapper_->addMapping(focalPointComboBox, 
                        EditProtocolsDialog::Protocol_FocalPointID);
    QSqlTableModel* displayPageModel = 
        model->relationModel(EditProtocolsDialog::Protocol_DisplayPageID);
    displayPageComboBox->setModel(displayPageModel);
    displayPageComboBox->setModelColumn(displayPageModel->fieldIndex("Name"));
    mapper_->addMapping(displayPageComboBox, 
                        EditProtocolsDialog::Protocol_DisplayPageID);
    mapper_->setCurrentIndex(row);

    connect(nameLineEdit, SIGNAL(textChanged(const QString&)),
            this, SLOT(enableOkButton()));
    buttonBox->button(QDialogButtonBox::Ok)->setDefault(false);
    enableOkButton();
}
Ejemplo n.º 25
0
// Предоставление редактора
QWidget*  ComboBoxFileldDelegate::createEditor ( QWidget * parent, const QStyleOptionViewItem & option,
												 const QModelIndex & index ) const
{
	if (index.column()>2){

		// QMessageBox::critical(0,"",index.model()->data(index.sibling(index.row(),0)).toString());
		QString pole = index.model()->data(index.sibling(index.row(),0)).toString();
		int j;
		for(int i=0;i<fieldName.count();i++){
				QString s = model->headerData( fieldName.at(i) , Qt::Horizontal).toString();
				s.replace("\n"," ");
				if (s==pole){
					j=fieldName.at(i);
					break;
				}
		}

		//QMessageBox::critical(0,"",QString("%1").arg(j));
		QSqlRelation rel =  model->relation(j);
		if (rel.indexColumn()!=QString("")){
			//QMessageBox::critical(0,"",rel.indexColumn()+" "+rel.displayColumn()+" "+rel.tableName());
			QComboBox * pRes = new QComboBox(parent);
			QSqlTableModel* relModel = new QSqlTableModel;

			relModel->setTable(rel.tableName());
			relModel->select();

			pRes->setModel(relModel);
			pRes->setModelColumn(relModel->fieldIndex(rel.displayColumn()));

			return pRes;

		}

		if (model->data(model->index(0,j), Qt::EditRole).type() == QVariant::Date){
			QDateEdit* pRes = new  QDateEdit(parent);
			pRes->setCalendarPopup(true);
			pRes->setDisplayFormat("dd.MM.yyyy");
			return pRes;
		}

		if (model->data(model->index(0,j), Qt::EditRole).type() == QVariant::Bool){
			QComboBox * pRes = new QComboBox(parent);

			pRes->addItem(tr("Нет"));
			pRes->addItem(tr("Да"));
			return pRes;
		}


		return QItemDelegate::createEditor(parent,option,index);
	}

	QComboBox * pRes = new QComboBox(parent);

	switch (index.column()) {
		case 0: {

			QStringList field;
			for(int i=0;i<fieldName.count();i++){
				QString s = model->headerData( fieldName.at(i) , Qt::Horizontal).toString();
				s.replace("\n"," ");
				field<<s;
			}
			pRes->addItems(field);
			break;
		}
		case 1: {
			pRes->addItem(tr(" "));
			pRes->addItem(tr("не"));
			break;
		}
		case 2: {
			pRes->addItem(tr("равно"));
			pRes->addItem(tr("похоже на"));
			pRes->addItem(tr("больше"));
			pRes->addItem(tr("меньше"));
			break;
		}

	}

	// это строка нужна для того чтобы по enter и esc завершалось редактирование итд
	pRes->installEventFilter(const_cast<ComboBoxFileldDelegate*>(this));

	return pRes;

};
Ejemplo n.º 26
0
void MainWindow::slotBtnReadCard()
{  
    std::string strTxtbrwInfos = "";
    QString strQTxtbrwInfos;
#ifdef USE_CH375
    if(ch375rw.bIsOpened)
    {
        ch375rw.Read(0x00,48);
        Sleep(TIME_DELAY);
        UCHAR *chData = ch375rw.Read(0x00,48);
        if(chData==NULL)
        {
            return;
        }
        strTxtbrwInfos = "卡号:"+ch375rw.strCardID+"\n";
        switch(int(chData[1]))//卡类型
        {
        case 0x01://用户卡
        {
            strTxtbrwInfos += "卡类型:用户卡\n";
            dsUserCard.chars2DS(chData);

            break;
        }
        case 0x2://普通管理人卡
            strTxtbrwInfos += "卡类型:普通管理人卡\n";
            break;
        case 0x3://高级管理人卡
            strTxtbrwInfos += "卡类型:高级管理人卡\n";
            break;
        case 0x04://黑名单(启禁用卡)
        {
            strTxtbrwInfos += "卡类型:启禁用卡\n";
            dsEnableCard.chars2DS(chData);
            if(dsEnableCard.structEnableCard.EnableType==0x01)//按卡号
            {
                strTxtbrwInfos += "启禁用类型:按卡号\n";
            }
            if(dsEnableCard.structEnableCard.EnableType==0x02)//按房号
            {
                strTxtbrwInfos += "启禁用类型:按房号\n";
            }
            std::string strLimitCardType="";
            if(dsEnableCard.structEnableCard.LimitCardType==0x01)
            {
                strLimitCardType="用户卡";
            }
            if(dsEnableCard.structEnableCard.LimitCardType==0x02)
            {
                strLimitCardType="管理人卡";
            }
            int nLiftNum = dsEnableCard.structEnableCard.LiftNum;
            strTxtbrwInfos +=
                "可用电梯:"+TypeConvert::intNormal2stdstring(nLiftNum)+"\n";
            if(dsEnableCard.structEnableCard.Num1[0]==0x00)
            {
                std::string strIsEnable1="";
                if(dsEnableCard.structEnableCard.IsEnable1==0x01)
                {
                    strIsEnable1="启用";
                }
                if(dsEnableCard.structEnableCard.IsEnable1==0x02)
                {
                    strIsEnable1="禁用";
                }
                std::string strNum1="";
                for(int i=0;i<4;i++)
                {
                    int nNum1=dsEnableCard.structEnableCard.Num1[i];
                    strNum1 += TypeConvert::intDec2stdstring(nNum1);
                }
                if(dsEnableCard.structEnableCard.EnableType==0x01)
                {
                    strTxtbrwInfos +=
                            strLimitCardType+"卡号:"+
                            strNum1.substr(3,5)+" "+strIsEnable1+"\n";
                }
                if(dsEnableCard.structEnableCard.EnableType==0x02)
                {
                    strTxtbrwInfos +=
                            "房号:"+strNum1.substr(4,4)+" "+strIsEnable1+"\n";
                }
            }
            if(dsEnableCard.structEnableCard.Num2[0]==0x00)
            {
                std::string strIsEnable2="";
                if(dsEnableCard.structEnableCard.IsEnable2==0x01)
                {
                    strIsEnable2="启用";
                }
                if(dsEnableCard.structEnableCard.IsEnable2==0x02)
                {
                    strIsEnable2="禁用";
                }
                std::string strNum2="";
                for(int i=0;i<4;i++)
                {
                    int nNum2=dsEnableCard.structEnableCard.Num2[i];
                    strNum2 += TypeConvert::intDec2stdstring(nNum2);
                }
                if(dsEnableCard.structEnableCard.EnableType==0x01)
                {
                    strTxtbrwInfos +=
                            strLimitCardType+"卡号:"+
                            strNum2.substr(3,5)+" "+strIsEnable2+"\n";
                }
                if(dsEnableCard.structEnableCard.EnableType==0x02)
                {
                    strTxtbrwInfos +=
                            "房号:"+strNum2.substr(4,4)+" "+strIsEnable2+"\n";
                }
            }
            if(dsEnableCard.structEnableCard.Num3[0]==0x00)
            {
                std::string strIsEnable3="";
                if(dsEnableCard.structEnableCard.IsEnable3==0x01)
                {
                    strIsEnable3="启用";
                }
                if(dsEnableCard.structEnableCard.IsEnable3==0x02)
                {
                    strIsEnable3="禁用";
                }
                std::string strNum3="";
                for(int i=0;i<4;i++)
                {
                    int nNum3=dsEnableCard.structEnableCard.Num3[i];
                    strNum3 += TypeConvert::intDec2stdstring(nNum3);
                }
                if(dsEnableCard.structEnableCard.EnableType==0x01)
                {
                    strTxtbrwInfos +=
                            strLimitCardType+"卡号:"+
                            strNum3.substr(3,5)+" "+strIsEnable3+"\n";
                }
                if(dsEnableCard.structEnableCard.EnableType==0x02)
                {
                    strTxtbrwInfos +=
                            "房号:"+strNum3.substr(4,4)+" "+strIsEnable3+"\n";
                }
            }
            if(dsEnableCard.structEnableCard.Num4[0]==0x00)
            {
                std::string strIsEnable4="";
                if(dsEnableCard.structEnableCard.IsEnable4==0x01)
                {
                    strIsEnable4="启用";
                }
                if(dsEnableCard.structEnableCard.IsEnable4==0x02)
                {
                    strIsEnable4="禁用";
                }
                std::string strNum4="";
                for(int i=0;i<4;i++)
                {
                    int nNum4=dsEnableCard.structEnableCard.Num4[i];
                    strNum4 += TypeConvert::intDec2stdstring(nNum4);
                }
                if(dsEnableCard.structEnableCard.EnableType==0x01)
                {
                    strTxtbrwInfos +=
                            strLimitCardType+"卡号:"+
                            strNum4.substr(3,5)+" "+strIsEnable4+"\n";
                }
                if(dsEnableCard.structEnableCard.EnableType==0x02)
                {
                    strTxtbrwInfos +=
                            "房号:"+strNum4.substr(4,4)+" "+strIsEnable4+"\n";
                }
            }
            break;
        }
        case 0x06://时间矫正卡
        {
            strTxtbrwInfos += "卡类型:时间矫正卡\n";
            dsTimeSet.chars2DS(chData);
            switch(dsTimeSet.structTimeSet.TimeSetType)
            {
            case SetType::SetControlerTime:
            {
                strTxtbrwInfos += "时间卡功能:控制器时间设置\n";               
                std::vector<std::string> vectorDateTime;
                for(int i=0;i<6;i++)
                {
                    int nTemp=dsTimeSet.structTimeSet.ControlerTime[i];
                    vectorDateTime.push_back(TypeConvert::intHex2stdstring(nTemp));
                }
                std::string strDateTime =
                        vectorDateTime[0]+    vectorDateTime[1]+"-"+
                        vectorDateTime[2]+"-"+vectorDateTime[3]+" "+
                        vectorDateTime[4]+":"+vectorDateTime[5];
                strTxtbrwInfos += "控制器时间:"+strDateTime+"\n";
                break;
            }
            case SetType::SetKeyResponseTime:
            {
                strTxtbrwInfos += "时间卡功能:按钮响应时间设置\n";
                float fTimeOne=
                        float(dsTimeSet.structTimeSet.SingleSelectTime)/10;
                short sTimeMul=dsTimeSet.structTimeSet.MultiSelectTime;
                std::string strTimeOne=TypeConvert::float2stdstring(fTimeOne);
                std::string strTimeMul=TypeConvert::intDec2stdstring(sTimeMul);
                strTxtbrwInfos +=
                        "单选按键响应时间:"+strTimeOne+"秒\n"+
                        "多选按键响应时间:"+strTimeMul+"秒\n";
                break;
            }
            case SetType::SetVisitorResponseTime:
            {
                strTxtbrwInfos += "时间卡功能:访客按钮响应时间设置\n";
                int nHI=dsTimeSet.structTimeSet.VisitorTime[0];
                int nLO=dsTimeSet.structTimeSet.VisitorTime[1];
                int nTimeVisit=nHI*256+nLO;
                std::string strTimeVisit =
                        TypeConvert::intNormal2stdstring(nTimeVisit);
                strTxtbrwInfos +=
                        "访客按键响应时间:"+strTimeVisit+"秒\n";
                break;
            }
            }
            break;
        }
        case 0x7://电梯运行卡
        {
            strTxtbrwInfos += "卡类型:电梯运行卡\n";
            break;
        }
        case 0x08://系统开关卡
        {
            strTxtbrwInfos += "卡类型:系统开关卡\n";
            dsSysSwitchCard.chars2DS(chData);
            switch (dsSysSwitchCard.structSysSwitchCard.SwitchCardType)
            {
            case SWCardType::SysSwitch:
            {
                strTxtbrwInfos+="开关卡分类:系统开关卡\n";
                break;
            }
            case SWCardType::LayerSwitch:
            {
                strTxtbrwInfos+="开关卡分类:分层开关卡\n";
                if(dsSysSwitchCard.structSysSwitchCard.SwitchFlag==0x11)
                {
                    strTxtbrwInfos+="开关标识:开放\n";
                }
                if(dsSysSwitchCard.structSysSwitchCard.SwitchFlag==0x22)
                {
                    strTxtbrwInfos+="开关标识:关闭\n";
                }
                //电梯编号
                int nLiftNum=0;
                for(int i=0;i<32;i++)
                {
                    for(int j=0;j<8;j++)
                    {
                        if
                        (
                        (dsSysSwitchCard.structSysSwitchCard.LiftNum[i] & (1<<j)) == pow(2,j)
                        )
                        {
                            nLiftNum=i*8+(j+1);
                            break;
                        }
                    }
                }
                strTxtbrwInfos+="可用电梯号:"+TypeConvert::intNormal2stdstring(nLiftNum)+"\n";
                //受控楼层
                strTxtbrwInfos+="受控楼层:";
                strTxtbrwInfos+="A门:";
                for(int i=0;i<6;i++)
                {
                    for(int j=0;j<8;j++)
                    {
                        if
                        (
                        (dsSysSwitchCard.structSysSwitchCard.FloorsA[i]&(1<<j)) == pow(2,j)
                        )
                        {
                            int nFloor = i*8+(j+1);
                            strTxtbrwInfos+=TypeConvert::intNormal2stdstring(nFloor)+",";
                        }
                    }
                }
                strTxtbrwInfos.erase(strTxtbrwInfos.end()-1);
                strTxtbrwInfos+="\n";
                break;
            }
            case SWCardType::PublicFloorsSet:
            {
                strTxtbrwInfos+="开关卡分类:公共楼层设置卡\n";
                if(dsSysSwitchCard.structSysSwitchCard.SwitchFlag==0x11)
                {
                    strTxtbrwInfos+="开关标识:开放\n";
                }
                if(dsSysSwitchCard.structSysSwitchCard.SwitchFlag==0x22)
                {
                    strTxtbrwInfos+="开关标识:关闭\n";
                }
                //电梯编号
                int nLiftNum=1;
                for(int i=0;i<32;i++)
                {
                    for(int j=0;j<8;j++)
                    {
                        if
                        (
                        (dsSysSwitchCard.structSysSwitchCard.LiftNum[i]&(1<<j)) == pow(2,j)
                        )
                        {
                            nLiftNum=i*8+(j+1);
                        }
                    }
                }
                strTxtbrwInfos+="可用电梯号:"+TypeConvert::intNormal2stdstring(nLiftNum)+"\n";
                //受控楼层
                strTxtbrwInfos+="受控楼层:";
                strTxtbrwInfos+="A门:";
                for(int i=0;i<6;i++)
                {
                    for(int j=0;j<8;j++)
                    {
                        if
                        (
                        (dsSysSwitchCard.structSysSwitchCard.FloorsA[i]&(1<<j)) == pow(2,j)
                        )
                        {
                            int nFloor = i*8+(j+1);
                            strTxtbrwInfos+=TypeConvert::intNormal2stdstring(nFloor)+",";
                        }
                    }
                }
                strTxtbrwInfos.erase(strTxtbrwInfos.end()-1);
                strTxtbrwInfos+="\n";
                break;
            }
            default:
                break;
            }
            break;
        }
        case 0x0A://通讯地址设定卡
        {
            strTxtbrwInfos += "卡类型:通讯地址设定卡\n";
            int nAddr = chData[2];
            strTxtbrwInfos +=
                    "地址:"+TypeConvert::intNormal2stdstring(nAddr)+"\n";
            break;
        }
        case 0x0B://清内存卡
        {
            strTxtbrwInfos += "卡类型:清内存卡\n";
            break;
        }     
        default:
        {
            strTxtbrwInfos += "此卡为新卡\n";
            break;
        }
        }
    }
    else
    {
        strTxtbrwInfos = "请插入读卡器!";
    }
    ch375rw.Beep(1);
    strQTxtbrwInfos=QString::fromStdString(strTxtbrwInfos);
#endif

    static int countClick=0;
    countClick++;
    switch(countClick)
    {
    case 1:
    {
        strQTxtbrwInfos="用户卡\n";
        std::vector<QString> arrFiledsUsrCards;
        arrFiledsUsrCards.push_back("卡号");
        arrFiledsUsrCards.push_back("业主姓名");
        arrFiledsUsrCards.push_back("业主门牌");
        arrFiledsUsrCards.push_back("联系电话");
        arrFiledsUsrCards.push_back("限制日期");
        arrFiledsUsrCards.push_back("可用电梯");
        arrFiledsUsrCards.push_back("可用楼层");
        arrFiledsUsrCards.push_back("房间编号");

        QSqlTableModel *modelTableUsrCard = new QSqlTableModel(this);
        modelTableUsrCard->setTable("tableUsrCard");
        modelTableUsrCard->select();
        int rowLast = modelTableUsrCard->rowCount()-1;
        for(int i=0;i<8;i++)
        {
            QModelIndex indexModelLast = modelTableUsrCard->index(rowLast,i);
            QString strUsrCardLast = modelTableUsrCard->data(indexModelLast).toString();
            strQTxtbrwInfos += arrFiledsUsrCards[i] + ":"+strUsrCardLast+"\n";
        }
        break;
    }
    case 2:
    {
        strQTxtbrwInfos="此卡为新卡!\n";
        break;
    }
    }

    txtbrwInfos->setText(strQTxtbrwInfos);
}
Ejemplo n.º 27
0
void sql_intro_snippets()
{
    {
//! [26]
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigblue");
    db.setDatabaseName("flightdb");
    db.setUserName("acarlson");
    db.setPassword("1uTbSbAs");
    bool ok = db.open();
//! [26]
    Q_UNUSED(ok);
    }

    {
//! [27]
    QSqlDatabase firstDB = QSqlDatabase::addDatabase("QMYSQL", "first");
    QSqlDatabase secondDB = QSqlDatabase::addDatabase("QMYSQL", "second");
//! [27]
    }

    {
//! [28]
    QSqlDatabase defaultDB = QSqlDatabase::database();
//! [28] //! [29]
    QSqlDatabase firstDB = QSqlDatabase::database("first");
//! [29] //! [30]
    QSqlDatabase secondDB = QSqlDatabase::database("second");
//! [30]
    }

    {
    // SELECT1
//! [31]
    QSqlQuery query;
    query.exec("SELECT name, salary FROM employee WHERE salary > 50000");
//! [31]

//! [32]
    while (query.next()) {
        QString name = query.value(0).toString();
        int salary = query.value(1).toInt();
        qDebug() << name << salary;
    }
//! [32]
    }

    {
    // FEATURE
//! [33]
    QSqlQuery query;
    int numRows;
    query.exec("SELECT name, salary FROM employee WHERE salary > 50000");

    QSqlDatabase defaultDB = QSqlDatabase::database();
    if (defaultDB.driver()->hasFeature(QSqlDriver::QuerySize)) {
        numRows = query.size();
    } else {
        // this can be very slow
        query.last();
        numRows = query.at() + 1;
    }
//! [33]
    }

    {
    // INSERT1
//! [34]
    QSqlQuery query;
    query.exec("INSERT INTO employee (id, name, salary) "
               "VALUES (1001, 'Thad Beaumont', 65000)");
//! [34]
    }

    {
    // NAMED BINDING
//! [35]
    QSqlQuery query;
    query.prepare("INSERT INTO employee (id, name, salary) "
                  "VALUES (:id, :name, :salary)");
    query.bindValue(":id", 1001);
    query.bindValue(":name", "Thad Beaumont");
    query.bindValue(":salary", 65000);
    query.exec();
//! [35]
    }

    {
    // POSITIONAL BINDING
//! [36]
    QSqlQuery query;
    query.prepare("INSERT INTO employee (id, name, salary) "
                  "VALUES (?, ?, ?)");
    query.addBindValue(1001);
    query.addBindValue("Thad Beaumont");
    query.addBindValue(65000);
    query.exec();
//! [36]
    }

    {
    // UPDATE1
//! [37]
    QSqlQuery query;
    query.exec("UPDATE employee SET salary = 70000 WHERE id = 1003");
//! [37]
    }

    {
    // DELETE1
//! [38]
    QSqlQuery query;
    query.exec("DELETE FROM employee WHERE id = 1007");
//! [38]
    }

    {
    // TRANSACTION
//! [39]
    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.exec("SELECT id FROM employee WHERE name = 'Torild Halvorsen'");
    if (query.next()) {
        int employeeId = query.value(0).toInt();
        query.exec("INSERT INTO project (id, name, ownerid) "
                   "VALUES (201, 'Manhattan Project', "
                   + QString::number(employeeId) + ')');
    }
    QSqlDatabase::database().commit();
//! [39]
    }

    {
    // SQLQUERYMODEL1
//! [40]
    QSqlQueryModel model;
    model.setQuery("SELECT * FROM employee");

    for (int i = 0; i < model.rowCount(); ++i) {
        int id = model.record(i).value("id").toInt();
        QString name = model.record(i).value("name").toString();
        qDebug() << id << name;
    }
//! [40]
    }

    {
    // SQLTABLEMODEL1
//! [41]
    QSqlTableModel model;
    model.setTable("employee");
    model.setFilter("salary > 50000");
    model.setSort(2, Qt::DescendingOrder);
    model.select();

    for (int i = 0; i < model.rowCount(); ++i) {
        QString name = model.record(i).value("name").toString();
        int salary = model.record(i).value("salary").toInt();
        qDebug() << name << salary;
    }
//! [41]
    }

    {
    // SQLTABLEMODEL2
    QSqlTableModel model;
    model.setTable("employee");

//! [42]
    for (int i = 0; i < model.rowCount(); ++i) {
        QSqlRecord record = model.record(i);
        double salary = record.value("salary").toInt();
        salary *= 1.1;
        record.setValue("salary", salary);
        model.setRecord(i, record);
    }
    model.submitAll();
//! [42]

    // SQLTABLEMODEL3
    int row = 1;
    int column = 2;
//! [43]
    model.setData(model.index(row, column), 75000);
    model.submitAll();
//! [43]

    // SQLTABLEMODEL4
//! [44]
    model.insertRows(row, 1);
    model.setData(model.index(row, 0), 1013);
    model.setData(model.index(row, 1), "Peter Gordon");
    model.setData(model.index(row, 2), 68500);
    model.submitAll();
//! [44]

//! [45]
    model.removeRows(row, 5);
//! [45] //! [46]
    model.submitAll();
//! [46]
    }
}
Ejemplo n.º 28
0
void loginFrame::readRegistryData()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("Registry.db");
    if(!db.open())
        return;
    //从数据库中读取ip
    //从数据库中读取自动登录的id,并自动登录
    QSqlTableModel *model3 = new QSqlTableModel();
    model3->setTable("serverip");
    if(model3->select())                //如果userlist表存在
    {
        QSqlRecord re = model3->record(0);
        QString serverip = re.value("ip").toString();
        ui->lineEdit_2->setText(serverip);
    }
    /////////////////////////////////
    //从数据库中读取自动登录的id,并自动登录
    QSqlTableModel *model2 = new QSqlTableModel();
    model2->setTable("autologin");
    QString autoid;
    if(!model2->select())                //如果userlist表不存在,则返回
        autoid = "0";
    QSqlRecord re = model2->record(0);
    autoid = re.value("id").toString();
    QString autoPasw = " ";
    int autoIndex = -1;
//    QTableView *view = new QTableView(this);
//    view->setModel(model2);
//    view->show();

    //从数据库中读取账号信息
    QSqlTableModel *model = new QSqlTableModel();
    model->setTable("userlist");
    if(!model->select())                //如果userlist表不存在,则返回
        return;
//    QTableView *view2 = new QTableView(this);
//    view2->setModel(model);
//    view2->show();
    int count = 0;
    for(int i=0;i<model->rowCount();i++)
    {
        QSqlRecord rec = model->record(i);
        QString id = rec.value("id").toString();
        QString username = QString::fromLocal8Bit(rec.value("username").toByteArray());
        QString password = QString::fromLocal8Bit(rec.value("password").toByteArray());
        UserInfo user;
        user.id = id;
        user.password = password;
        user.username = username;
        RegistyShowID.append(user);
        count++;
        ui->comboBox->insertItem(count,QIcon(":/images/head.png"),id);
        if(id == autoid)                 //找出自动登录id的index
        {
            autoIndex = i;
            autoPasw = password;
        }
    }
    if(autoid != " " && autoIndex >=0)   //若为" ",则没有自动登录的id
    {
        ui->comboBox->setCurrentIndex(autoIndex);
        if(autoPasw != " ")
            ui->lineEdit_Password->setText(autoPasw);
        this->isauto = true;             //自动登录
    }
}
Ejemplo n.º 29
-1
CollectionTreeWidgetItem *CollectionTreeWidget::addMusic(Music *music, unsigned int id) {
    // Find id in database if we don't have it
    if (id == 0) {
         QSqlTableModel *model = service->collectionModel();

         // SQLite used two single quotes to escape a single quote! :)
         QString filter = "artist = '" + music->getArtist().replace("'","''") + "' AND "
                          "album = '" + music->getAlbum().replace("'","''") + "' AND "
                          "music = '" + music->getTitle().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_music")).toInt();
         }
         else {
             qDebug("ERROR: no songs found! -- " + model->filter().toUtf8());
             return NULL;
         }
    }

    // Looks for the album
    QTreeWidgetItem *albumItem = addAlbum(music->getArtist(), music->getAlbum());

    // Create our new music node and add it if it was not found
    removeMusic(id);

    CollectionTreeWidgetItem *newMusicNode = new CollectionTreeWidgetItem(LevelMusic, id, (QTreeWidget*)0);
    newMusicNode->setText(0, music->getTitle());
    newMusicNode->setIcon(0, IconFactory::fromTheme("sound"));
    albumItem->addChild(newMusicNode);
    musicList.append(newMusicNode);

    return newMusicNode;
}
Ejemplo n.º 30
-1
void FormGestioneFerie::on_tvPermessi_doubleClicked(const QModelIndex &index)
{

    if(index.column()==2)
    {
        QMessageBox msgBox;
        msgBox.setText("Cancella assenza programmata.");
        msgBox.setInformativeText(QString("Cancellare l'assenza programmata di %2 per il giorno %1 ?").arg(index.data().toString()).arg(ui->cbCognome->currentText()));
        msgBox.setStandardButtons(QMessageBox::Apply |QMessageBox::Discard  );
        msgBox.setIcon(QMessageBox::Question);
        int ret = msgBox.exec();
        if (ret==QMessageBox::Apply )
        {
            QSqlQuery query(QString("DELETE FROM assenze where id=\"%1\"").arg(ui->cbMatricola->currentText()+"_"+index.data().toString()));
            query.exec();
            qDebug() << query.lastError();

            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);
        }
    }

}