コード例 #1
0
void mySqlRelationalDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if (!index.isValid())
        return;

    QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel *>(model);
    QSortFilterProxyModel* proxyModel = NULL;
    if (!sqlModel )
    {
        proxyModel = qobject_cast<QSortFilterProxyModel *>(model);
        if (proxyModel)
             sqlModel = qobject_cast<QSqlRelationalTableModel *>(proxyModel->sourceModel());
    }

    QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0;
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    if (!sqlModel || !childModel || !combo) {
        QItemDelegate::setModelData(editor, model, index);
        return;
    }

    int currentItem = combo->currentIndex();
    int childColIndex = childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn());
    int childEditIndex = childModel->fieldIndex(sqlModel->relation(index.column()).indexColumn());


    if (proxyModel) {
        proxyModel->setData(index, childModel->data(childModel->index(currentItem, childColIndex), Qt::DisplayRole), Qt::DisplayRole);
        proxyModel->setData(index, childModel->data(childModel->index(currentItem, childEditIndex), Qt::EditRole), Qt::EditRole);
    } else {
        sqlModel->setData(index, childModel->data(childModel->index(currentItem, childColIndex), Qt::DisplayRole), Qt::DisplayRole);
        sqlModel->setData(index, childModel->data(childModel->index(currentItem, childEditIndex), Qt::EditRole), Qt::EditRole);
    }
}
コード例 #2
0
void SupplierManageWindow::areaUpdateCombo(bool select)
{
    QSqlTableModel *ptrModel = m_model->relationModel(SupplierManageWindow::idArea);
    if(select)
	ptrModel->select();
    ptrModel->insertRow(0);
    ptrModel->setData(ptrModel->index(0, ptrModel->fieldIndex("name")),
      trUtf8("-- Seleccione Rubro --"), Qt::EditRole);
    cb_area->setModel(ptrModel);
    cb_area->setModelColumn(ptrModel->fieldIndex("name"));
    cb_area->setCurrentIndex(0);
}
コード例 #3
0
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);
}
コード例 #4
0
QWidget *MySqlRelationDelegate::createEditor(QWidget *aParent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    const QSqlRelationalTableModel *sqlModel = qobject_cast<const QSqlRelationalTableModel *>(index.model());
    QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0;
    if (!childModel)
    {
        if (HandbookDialog::m_record.fieldName(index.column()).contains("IS_", Qt::CaseSensitive))
        {
            QCheckBox * checkBox = new QCheckBox(aParent);
            checkBox->setChecked(index.data().toInt() > 0);
            return checkBox;
        }
        else if (HandbookDialog::m_record.fieldName(index.column()).contains("DATE_", Qt::CaseSensitive))
        {
            QDateEdit * dateEdit = new QDateEdit(aParent);
            dateEdit->setDate(QDate::fromString(index.data().toString(), "yyyy-MM-dd"));
            return dateEdit;
        }
        else
        {
            return QItemDelegate::createEditor(aParent, option, index);
        }
    }

    QComboBox *combo = new QComboBox(aParent);
    combo->setModel(childModel);
    combo->setModelColumn(childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn()));
    combo->installEventFilter(const_cast<MySqlRelationDelegate *>(this));

    return combo;
}
コード例 #5
0
void XComboBox::setDataWidgetMap(XDataWidgetMapper* m)
{
  disconnect(this, SIGNAL(editTextChanged(QString)), this, SLOT(updateMapperData()));
  disconnect(this, SIGNAL(newID(int)), this, SLOT(updateMapperData()));

  if (!_listTableName.isEmpty())
  {
    QString tableName="";
    if (_listSchemaName.length())
      tableName=_listSchemaName + ".";
    tableName+=_listTableName;
    static_cast<XSqlTableModel*>(m->model())->setRelation(static_cast<XSqlTableModel*>(m->model())->fieldIndex(_fieldName),
                                 QSqlRelation(tableName, _listIdFieldName, _listDisplayFieldName));

    QSqlTableModel *rel =static_cast<XSqlTableModel*>(m->model())->relationModel(static_cast<XSqlTableModel*>(m->model())->fieldIndex(_fieldName));
    setModel(rel);
    setModelColumn(rel->fieldIndex(_listDisplayFieldName));

    m->setItemDelegate(new QSqlRelationalDelegate(this));
    m->addMapping(this, _fieldName);
    return;
  }
  else if (_codes.count())
    m->addMapping(this, _fieldName, "code", "currentDefault");
  else
    m->addMapping(this, _fieldName, "text", "text");

  _mapper=m;
  connect(this, SIGNAL(editTextChanged(QString)), this, SLOT(updateMapperData()));
  connect(this, SIGNAL(newID(int)), this, SLOT(updateMapperData()));
}
コード例 #6
0
EncuestadorPickForm::EncuestadorPickForm(QWidget *parent) :
    QDialog(parent){
    setupUi(this);
    mapper = new QDataWidgetMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);

    model = new QSqlRelationalTableModel(this);
    model->setTable("encuestador");
    model->setRelation(1, QSqlRelation("titulo_encuestador","id","descripcion"));
    model->select();

    QSqlTableModel *relModel = model->relationModel(1);
    tituloCmb->setModel(relModel);
    tituloCmb->setModelColumn(relModel->fieldIndex("descripcion"));

    mapper->setModel(model);
    mapper->setItemDelegate(new QSqlRelationalDelegate(this));
    mapper->addMapping(tituloCmb, 1);
    mapper->addMapping(nombreEdit, 2);
    mapper->addMapping(apellidoEdit, 3);

    int row = model->rowCount();
    model->insertRow(row);
    mapper->setCurrentIndex(row);
    tituloCmb->setCurrentIndex(0);
}
コード例 #7
0
QWidget *mySqlRelationalDelegate::createEditor(QWidget *aParent, const QStyleOptionViewItem &option, const QModelIndex &index) const {

    const QSqlRelationalTableModel *sqlModel = qobject_cast<const QSqlRelationalTableModel *>(index.model());
    QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0;

    if (!childModel )
    {
        const QSortFilterProxyModel* proxyModel = qobject_cast<const QSortFilterProxyModel *>(index.model());
        if (proxyModel)
        {
            sqlModel = qobject_cast<const QSqlRelationalTableModel *>(proxyModel->sourceModel());
            childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0;
        }
    }

    if (!childModel)
    {
        return QItemDelegate::createEditor(aParent, option, index);
    }

    QComboBox *combo = new QComboBox(aParent);
    combo->setModel(childModel);
    combo->setModelColumn(childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn()));
    combo->installEventFilter(const_cast<mySqlRelationalDelegate *>(this));

    return combo;

}
コード例 #8
0
/// @brief Constructor
CollectionTreeWidget::CollectionTreeWidget()
{
    setColumnCount(1);
    header()->hide(); // hide headers
    setDragEnabled(true);
    setAcceptDrops(true);
    setSelectionMode(QAbstractItemView::ExtendedSelection);

    service = new CollectionService();

    // Add songs that currently exist on database
    QSqlTableModel *artistModel = service->artistModel();
    artistModel->select();

    // TODO: verify if we can put fetchmore() inside the for loop.
    // TODO: put this task in background... URGENT
    while (artistModel->canFetchMore()) artistModel->fetchMore();
    int total = artistModel->rowCount();

    for (int i = 0; i < total; i++) {
        QString artist = artistModel->record(i).value(artistModel->fieldIndex("name")).toString();
        unsigned int id = artistModel->record(i).value(artistModel->fieldIndex("id")).toInt();
        addArtist(artist, id);
    }
    delete artistModel;

    /*
     * TODO: modify the slots in order to add only the artist, not the music.
     *       The album and song must be shown only if the node is already expanded.
     */
    connect(service, SIGNAL(songAdded(Music*)), this, SLOT(addMusic(Music*)));
    connect(service, SIGNAL(songRemoved(unsigned int)), this, SLOT(removeMusic(uint)));
    connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(doubleClickAt(QModelIndex)));
    connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(showChildrenOf(QModelIndex)));

    /*
     * We shall emit those signals to show or hide the widget that will
     * give the feedback that the collection is being scanned.
     */
    connect(service, SIGNAL(scanning()), this, SIGNAL(scanning()));
    connect(service, SIGNAL(listUpdated()), this, SIGNAL(listUpdated()));

    // Start service to find new songs and remove the inexistent ones
    service->start(QThread::LowestPriority);
}
コード例 #9
0
ファイル: window.cpp プロジェクト: cedrus/qt4
//! [Set up widgets]
Window::Window(QWidget *parent)
    : QWidget(parent)
{
    setupModel();

    nameLabel = new QLabel(tr("Na&me:"));
    nameEdit = new QLineEdit();
    addressLabel = new QLabel(tr("&Address:"));
    addressEdit = new QTextEdit();
    typeLabel = new QLabel(tr("&Type:"));
    typeComboBox = new QComboBox();
    nextButton = new QPushButton(tr("&Next"));
    previousButton = new QPushButton(tr("&Previous"));

    nameLabel->setBuddy(nameEdit);
    addressLabel->setBuddy(addressEdit);
    typeLabel->setBuddy(typeComboBox);
//! [Set up widgets]

//! [Set up the mapper]
    QSqlTableModel *relModel = model->relationModel(typeIndex);
    typeComboBox->setModel(relModel);
    typeComboBox->setModelColumn(relModel->fieldIndex("description"));

    mapper = new QDataWidgetMapper(this);
    mapper->setModel(model);
    mapper->setItemDelegate(new QSqlRelationalDelegate(this));
    mapper->addMapping(nameEdit, model->fieldIndex("name"));
    mapper->addMapping(addressEdit, model->fieldIndex("address"));
    mapper->addMapping(typeComboBox, typeIndex);
//! [Set up the mapper]

//! [Set up connections and layouts]
    connect(previousButton, SIGNAL(clicked()),
            mapper, SLOT(toPrevious()));
    connect(nextButton, SIGNAL(clicked()),
            mapper, SLOT(toNext()));
    connect(mapper, SIGNAL(currentIndexChanged(int)),
            this, SLOT(updateButtons(int)));

    QGridLayout *layout = new QGridLayout();
    layout->addWidget(nameLabel, 0, 0, 1, 1);
    layout->addWidget(nameEdit, 0, 1, 1, 1);
    layout->addWidget(previousButton, 0, 2, 1, 1);
    layout->addWidget(addressLabel, 1, 0, 1, 1);
    layout->addWidget(addressEdit, 1, 1, 2, 1);
    layout->addWidget(nextButton, 1, 2, 1, 1);
    layout->addWidget(typeLabel, 3, 0, 1, 1);
    layout->addWidget(typeComboBox, 3, 1, 1, 1);
    setLayout(layout);

    setWindowTitle(tr("SQL Widget Mapper"));
    mapper->toFirst();
}
コード例 #10
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);
}
コード例 #11
0
void MainWindow::on_currencyComboBox_currentIndexChanged(int index)
{
    int row = ui->assetsTable->currentIndex().row();
    QVariant current_value = model->data(model->index(row, currency_column_index), Qt::DisplayRole);

    QSqlTableModel *childModel = model->relationModel(currency_column_index);
    int childColIndex = childModel->fieldIndex("code");
    QVariant new_value = childModel->data(childModel->index(index, childColIndex), Qt::DisplayRole);

    if(current_value != new_value) {
        mapper->submit();
    }
}
コード例 #12
0
ファイル: control.cpp プロジェクト: Mr-Phoebe/QT-learning
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);
}
コード例 #13
0
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;
}
コード例 #14
0
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();
    }
}
コード例 #15
0
ファイル: dialogvibsotr.cpp プロジェクト: roandbox/profimax
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"));

}
コード例 #16
0
ファイル: carsedit.cpp プロジェクト: Berimor66/humblemaps
void CarsEdit::FillTable()
{
    QString str_oper = "SELECT hm_cars.id, hm_cars.name, hm_cars.speed, hm_fuel.name, hm_fuel.id FROM hm_cars INNER JOIN hm_fuel ON hm_cars.fuel_id = hm_fuel.id;";
    QSqlQueryModel * model_Oper = new QSqlQueryModel(0);
    model_Oper->setQuery(str_oper);
    model_Oper->setHeaderData(1, Qt::Horizontal, QObject::trUtf8("Название автомобиля"));
    model_Oper->setHeaderData(2, Qt::Horizontal, QObject::trUtf8("Максимальная скорость"));
    model_Oper->setHeaderData(3, Qt::Horizontal, QObject::trUtf8("Тип топлива"));
    ui->tableView->setModel(model_Oper);
    ui->tableView->hideColumn(0);
    ui->tableView->hideColumn(4);

    QSqlRelationalTableModel *comboModel = new QSqlRelationalTableModel(0);
    comboModel->setTable("hm_fuel");
    int comboIndex = comboModel->fieldIndex("id");
    comboModel->setRelation(comboIndex, QSqlRelation("hm_fuel", "id", "name"));
    comboModel->select();
    QSqlTableModel *comboRelModel = comboModel->relationModel(comboIndex);
    ui->comboBox->setModel(comboRelModel);
    ui->comboBox->setModelColumn(comboRelModel->fieldIndex("name"));
}
コード例 #17
0
void XComboBox::setDataWidgetMap(XDataWidgetMapper* m)
{
  if (!_listTableName.isEmpty())
  {
    QString tableName="";
    if (_listSchemaName.length())
      tableName=_listSchemaName + ".";
    tableName+=_listTableName;
    static_cast<XSqlTableModel*>(m->model())->setRelation(static_cast<XSqlTableModel*>(m->model())->fieldIndex(_fieldName), 
                                 QSqlRelation(tableName, _listIdFieldName, _listDisplayFieldName));
    
    QSqlTableModel *rel =static_cast<XSqlTableModel*>(m->model())->relationModel(static_cast<XSqlTableModel*>(m->model())->fieldIndex(_fieldName));
    setModel(rel);
    setModelColumn(rel->fieldIndex(_listDisplayFieldName));
  
    m->setItemDelegate(new QSqlRelationalDelegate(this));
    m->addMapping(this, _fieldName);
  }
  else if (_codes.count())
    m->addMapping(this, _fieldName, "code", "currentDefault");
  else
    m->addMapping(this, _fieldName, "text", "text");
}
コード例 #18
0
ModuloUsuarios::ModuloUsuarios(QWidget *parent) :
  ModuleInterface(parent,new ui_usuario_datos)
{
  Ui::ui_usuario_datos * data_ui = (((ui_usuario_datos*)detalles_tab)->getUI());
  connect(data_ui->pB_cambiarPass,SIGNAL(clicked()),SLOT(CambiarPass()));
  relTableModel->setTable("colaborador");
  relTableModel->setHeaderData(1,Qt::Horizontal,"Nombres");
  relTableModel->setHeaderData(2,Qt::Horizontal,"Apellido Paterno");
  relTableModel->setHeaderData(3,Qt::Horizontal,"Apellido Materno");
  relTableModel->setRelation(4,QSqlRelation("tipo_colaborador","idtipo_colaborador","nombre"));
  relTableModel->setHeaderData(4,Qt::Horizontal,"Tipo Colaborador");
  relTableModel->setRelation(5,QSqlRelation("tienda","idtienda","alias"));
  relTableModel->setHeaderData(5,Qt::Horizontal,"Tienda");
  relTableModel->setHeaderData(6,Qt::Horizontal,"Nombre Usuario");
  relTableModel->setRelation(7,QSqlRelation("SiNo","id","value"));
  relTableModel->setHeaderData(7,Qt::Horizontal,"Habilitado");
  relTableModel->setRelation(8,QSqlRelation("SiNo","id","value"));
  relTableModel->setHeaderData(8,Qt::Horizontal,"Cambiar Pass.");
  relTableModel->setRelation(9,QSqlRelation("tipodoc_ident","idtipodoc_ident","nombre"));
  relTableModel->setHeaderData(9,Qt::Horizontal,"Tipo D.I.");
  relTableModel->setHeaderData(10,Qt::Horizontal,"Nro Doc.");
  relTableModel->setHeaderData(11,Qt::Horizontal,"Direción");
  relTableModel->setHeaderData(12,Qt::Horizontal,"Fecha Nac.");
  relTableModel->setHeaderData(13,Qt::Horizontal,"Telefono");
  relTableModel->setHeaderData(14,Qt::Horizontal,"Telf. Fam.");
  relTableModel->setHeaderData(15,Qt::Horizontal,"Celular");
  relTableModel->setHeaderData(16,Qt::Horizontal,"Observaciones");

  QSqlTableModel *relationModel = relTableModel->relationModel(4);
  data_ui->cB_tipoCol->setModel(relationModel);
  data_ui->cB_tipoCol->setModelColumn(relationModel->fieldIndex("nombre"));
  relationModel = relTableModel->relationModel(5);
  data_ui->cb_tienda->setModel(relationModel);
  data_ui->cb_tienda->setModelColumn(relationModel->fieldIndex("alias"));
  relationModel = relTableModel->relationModel(9);
  data_ui->cB_tDoc->setModel(relationModel);
  data_ui->cB_tDoc->setModelColumn(relationModel->fieldIndex("nombre"));

  mapper->setModel(relTableModel);
  mapper->setItemDelegate(new QSqlRelationalDelegate);
  mapper->addMapping(data_ui->le_nombre,1);
  mapper->addMapping(data_ui->le_pApellido,2);
  mapper->addMapping(data_ui->le_sApellido,3);
  mapper->addMapping(data_ui->cB_tipoCol,4);
  mapper->addMapping(data_ui->cb_tienda,5);
  mapper->addMapping(data_ui->le_Usuario,6);
  mapper->addMapping(data_ui->checkBox_habilitado,7);
  mapper->addMapping(data_ui->cB_tDoc,9);
  mapper->addMapping(data_ui->le_numDoc,10);
  mapper->addMapping(data_ui->le_direccion,11);
  mapper->addMapping(data_ui->de_fechaNac,12);
  mapper->addMapping(data_ui->le_telf,13);
  mapper->addMapping(data_ui->lE_telfFam,14);
  mapper->addMapping(data_ui->le_cell,15);
  mapper->addMapping(data_ui->tE_obs,16);

  data_ui->tableView_permisos->setItemDelegateForColumn(3,new QSqlRelationalDelegate);
  data_ui->tableView_permisos->setItemDelegateForColumn(2,new NoEditItemDelegate);
  ConfigPermisosModelView();
  relTableModel->select();
  if(relTableModel->lastError().isValid())
    QMessageBox::critical(this,"Error",relTableModel->lastError().text(),0,0);
  ui->list_tableView->setModel(relTableModel);
  QItemSelectionModel * sm = ui->list_tableView->selectionModel();
  connect(sm,SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),this,SLOT(selectionChangedHandle(QModelIndex,QModelIndex)));
  ui->list_tableView->hideColumn(0);
  ui->list_tableView->hideColumn(17);
}
コード例 #19
0
MovimentoEditDialog::MovimentoEditDialog(QSqlRelationalTableModel* model,
													  ColumnIndexes & colInd,
													  int curRow,
													  bool canSubmit, QWidget *parent)
	: QDialog(parent)
	, ui(new Ui::MovimentoEditDialog)
	, m_movModel(model)
	, m_insert(curRow<0) // se linha < 0, então é inserção, do contrário é edição
	, m_canSubmit(canSubmit)
	, m_colInd(colInd)
{
	ui->setupUi(this);


	if ( m_insert )
		ui->movimentoNavGroup->hide(); // se vai inserir, não haverá havegação.

	// seta as comboBox para que sejam alimentadas pelo relacionamento correspondente
	// exibindo a coluna "nome" ao inves de "id":

	// nomes de clientes na respectiva combo:
	QSqlTableModel *cliRelationModel =
									m_movModel->relationModel(m_colInd.movClienteId);
	ui->clienteCombo->setModel(cliRelationModel);
	ui->clienteCombo->setModelColumn(cliRelationModel->fieldIndex("name"));
	// como o relation model só duas colunas (chave e valor), poderia:
	//ui->clienteCombo->setModelColumn(1); // índice da coluna valor
	
	ui->clienteCombo->model()->sort(cliRelationModel->fieldIndex("name"), Qt::AscendingOrder);

	// tipos de movimento na respectiva combo:
	QSqlTableModel *tipoRelationModel = m_movModel->relationModel(m_colInd.movTipoId);
	ui->tipoCombo->setModel(tipoRelationModel);
	ui->tipoCombo->setModelColumn(tipoRelationModel->fieldIndex("name"));
	ui->tipoCombo->model()->sort(tipoRelationModel->fieldIndex("name"), Qt::AscendingOrder);

	// * ^^ Nos 2 "relationModel" acima, temos sempre duas colunas: "chave" e "valor associado".

	// cria um mapeador que relacionará widgets "sem-model" com
	// as colunas respectivas do model:
	m_movMapper = new QDataWidgetMapper(this);

	// "submitPolicy": "auto" ou "manual"; se "auto" irá completar alterações se a linha selecionada for alterada
	m_movMapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); // "manual" -> teremos que chamar "submit" no momento apropriado.
	// define o "model" a ser usado pelo "mapper":
	m_movMapper->setModel(m_movModel);
	// define o delegate que permite exibir colunas relacionadas em comboBox's
	m_movMapper->setItemDelegate(new QSqlRelationalDelegate(this));

	// mapeia cada widget necessário para a coluna respectiva no model:
	m_movMapper->addMapping(ui->clienteCombo, m_colInd.movClienteId);
	m_movMapper->addMapping(ui->tipoCombo, m_colInd.movTipoId);
	m_movMapper->addMapping(ui->movDate, m_colInd.movDate);
	m_movMapper->addMapping(ui->descrEdit, m_colInd.movDescription);

	// conecta os botões de navegação diretamente aos slots do "mapper"
	// (neste caso, não é necessário criar novos slots para isso, exceto se quisermos fazer algo diferenciado)
	if ( !m_insert )
	{
		connect(ui->movimentoNavFirstBtn, SIGNAL(clicked()),
																			m_movMapper, SLOT(toFirst()));
		connect(ui->movimentoNavPrevBtn, SIGNAL(clicked()),
																			m_movMapper, SLOT(toPrevious()));
		connect(ui->movimentoNavNextBtn, SIGNAL(clicked()),
																			m_movMapper, SLOT(toNext()));
		connect(ui->movimentoNavLastBtn, SIGNAL(clicked()),
																			m_movMapper, SLOT(toLast()));
	}

	// se for inserir, deve criar nova linha no model
	if ( m_insert ) // INSERIR
	{
		// insere uma nova linha no model (caso o insert seja cancelado, deverá ser removida):
		curRow = m_movModel->rowCount(); // altera curRow para o total de linhas
		// rowCount -> total de linhas -> uma nova linha no final:
		m_movModel->insertRow(curRow);

		// em inclusão, seta widgets de data (para forçar o default):
		ui->movDate->setDate( QDate::currentDate() );

		setWindowTitle("INCLUIR novo movimento - "); // título do diálogo
	}
	else  // ALTERAR
		setWindowTitle("ALTERAR um movimento - ");  // título do diálogo

	QSqlDatabase db = m_movModel->database();
	setWindowTitle( windowTitle() + db.driverName());

	m_movMapper->setCurrentIndex(curRow); // seta a "row" do mapper

	// desabilta a opção do menu de sistema "fechar" ("X");
	// desse modo só poderá fechar o diálogo com os botões "OK" e "CANCELAR"
	// e não precisaremos redefinir a virtual "closeEvent" para finalzação
	Qt::WindowFlags flags = windowFlags();
	flags |=  Qt::CustomizeWindowHint;  // acrescenta: flags customizados
	flags &= ~Qt::WindowCloseButtonHint;  // desabilita: closeButton
	setWindowFlags(flags);

}
コード例 #20
0
ファイル: employeeform.cpp プロジェクト: marvinfy/Trainings
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"));
}
コード例 #21
0
ファイル: dialogkvp.cpp プロジェクト: roandbox/profimax
void DialogKvp::setModel(ProfimaxRelationalModel* modd) {



	modelSotr->setTable("prof_sotr");
	modelSotr->setRelation(30, QSqlRelation("prof_dolgn", "dolgn_id", "name"));
	modelSotr->select();

	QSqlTableModel* relModel = modelSotr->relationModel(modelSotr->fieldIndex("dolgn_id"));
	comboBoxDolgn->setModel(relModel);
	comboBoxDolgn->setModelColumn(relModel->fieldIndex("name"));

	mapperSotr->setModel(modelSotr);
	mapperSotr->setItemDelegate(new QSqlRelationalDelegate());

	// Main Page
	//mapperSotr->addMapping(toolButtonFoto, modelSotr->fieldIndex("foto"));
	mapperSotr->addMapping(lineEditLastName, modelSotr->fieldIndex("lastname"));
	mapperSotr->addMapping(lineEditFirstName, modelSotr->fieldIndex("firstname"));
	mapperSotr->addMapping(lineEditMidName, modelSotr->fieldIndex("midname"));

	mapperSotr->addMapping(lineEditCity, modelSotr->fieldIndex("city"));
	mapperSotr->addMapping(spinBoxPost, modelSotr->fieldIndex("post"));
	mapperSotr->addMapping(lineEditStreet, modelSotr->fieldIndex("street"));
	mapperSotr->addMapping(spinBoxHouse, modelSotr->fieldIndex("house"));
	mapperSotr->addMapping(spinBoxCase, modelSotr->fieldIndex("case"));
	mapperSotr->addMapping(spinBoxFlat, modelSotr->fieldIndex("flat"));

	mapperSotr->addMapping(spinBoxTabNum, modelSotr->fieldIndex("tabnum"));
	mapperSotr->addMapping(comboBoxDolgn, modelSotr->fieldIndex("dolgn_id"));
	//mapperSotr->addMapping(comboBoxOtdel->comboBox, modelSotr->fieldIndex("otdel_id"));

	mapperSotr->addMapping(spinBoxPaspNum, modelSotr->fieldIndex("pasp_num"));
	mapperSotr->addMapping(spinBoxPaspSer, modelSotr->fieldIndex("pasp_ser"));
	mapperSotr->addMapping(dateEditPaspDate, modelSotr->fieldIndex("pasp_date"));
	mapperSotr->addMapping(lineEditPaspPlace, modelSotr->fieldIndex("pasp_place"));
	mapperSotr->addMapping(spinBoxStage, modelSotr->fieldIndex("stage"));

	// TableView для телефона
	tableViewTel->setTable("prof_tel");
	tableViewTel->model->setEditStrategy(QSqlTableModel::OnManualSubmit);
	tableViewTel->setButtoIconSize(16);
	tableViewTel->toolButtonFilter->hide();
	tableViewTel->toolButtonEdit->hide();
	tableViewTel->lineToolView2->hide();
	tableViewTel->setMargin(2);
	tableViewTel->model->setRelation(1,  QSqlRelation("prof_teltype", "teltype_id", "name"));
	tableViewTel->select();

	QStringList headName;
	headName << "teltype_id"<< "nomer";
	tableViewTel->setSortColumn(headName);
	tableViewTel->setHeader("teltype_id", tr("Тип"));
	tableViewTel->setHeader("nomer", tr("Ноиер"));
	tableViewTel->show();


	//---------- ПОРУЧИТЕЛЬ ----------
	if (model->tableName()!="prof_kvp"){
		modelins = new ProfimaxRelationalModel();
		modelins->setTable("prof_kvp_view");
		modelins->select();
		modelins->setEditStrategy(QSqlTableModel::OnRowChange);
		model = modelins;
	} else {
	    model = modd;
	}

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

	mapper->addMapping(lineEditLastNameP, model->fieldIndex("plastname"));
	mapper->addMapping(lineEditFirstNameP, model->fieldIndex("pfirstname"));
	mapper->addMapping(lineEditMidNameP, model->fieldIndex("pmidname"));

	mapper->addMapping(lineEditCityP, model->fieldIndex("pcity"));
	mapper->addMapping(spinBoxPostP, model->fieldIndex("ppost"));
	mapper->addMapping(lineEditStreetP, model->fieldIndex("pstreet"));
	mapper->addMapping(spinBoxHouseP, model->fieldIndex("phouse"));
	mapper->addMapping(spinBoxCaseP, model->fieldIndex("pcase"));
	mapper->addMapping(spinBoxFlatP, model->fieldIndex("pflat"));

	mapper->addMapping(spinBoxPaspNumP, model->fieldIndex("ppasp_num"));
	mapper->addMapping(spinBoxPaspSerP, model->fieldIndex("ppasp_ser"));
	mapper->addMapping(dateEditPaspDateP, model->fieldIndex("ppasp_date"));
	mapper->addMapping(lineEditPaspPlaceP, model->fieldIndex("ppasp_place"));

	mapper->addMapping(lineEditDolgmP, model->fieldIndex("pdolgn"));
	mapper->addMapping(lineEditRabotaP, model->fieldIndex("prabota"));
	mapper->addMapping(lineEditDogNumP, model->fieldIndex("pdog_num"));
	mapper->addMapping(dateEditDogDateP, model->fieldIndex("pdog_date"));

	// TableView для телефона
	tableViewTelP->setTable("prof_kvptel");
	tableViewTelP->model->setEditStrategy(QSqlTableModel::OnManualSubmit);
	tableViewTelP->setButtoIconSize(16);
	tableViewTelP->toolButtonFilter->hide();
	tableViewTelP->toolButtonEdit->hide();
	tableViewTelP->lineToolView2->hide();
	tableViewTelP->setMargin(2);
	tableViewTelP->model->setRelation(1,  QSqlRelation("prof_teltype", "teltype_id", "name"));
	tableViewTelP->select();

	headName << "teltype_id"<< "nomer";
	tableViewTelP->setSortColumn(headName);
	tableViewTelP->setHeader("teltype_id", tr("Тип"));
	tableViewTelP->setHeader("nomer", tr("Ноиер"));
	tableViewTelP->show();



	mapper->addMapping(dateEditDocDate, model->fieldIndex("doc_date"));
	mapper->addMapping(lineEditBank, model->fieldIndex("bank"));
	mapper->addMapping(lineEditDogNumS, model->fieldIndex("dogssoud_num"));
	mapper->addMapping(dateEditDugDateS, model->fieldIndex("dogssoud_date"));
	mapper->addMapping(lineEditProtokolNum, model->fieldIndex("protokol_num"));
	mapper->addMapping(dateEditProtokolDate, model->fieldIndex("protokol_date"));
	mapper->addMapping(lineEditSchetNum, model->fieldIndex("schet"));
	mapper->addMapping(lineEditNazS, model->fieldIndex("nazn"));
	mapper->addMapping(lineEditSummaS, model->fieldIndex("text_summa"));
	mapper->addMapping(lineEditSrokS, model->fieldIndex("text_srok"));
	mapper->addMapping(dateEditMonthS, model->fieldIndex("begin_date"));
	mapper->addMapping(lineEditOtkazS, model->fieldIndex("otkaz"));
	mapper->addMapping(spinBoxSummaS, model->fieldIndex("summa"));
	mapper->addMapping(spinBoxSrokS, model->fieldIndex("srok"));

	model = modd;


}
コード例 #22
0
ファイル: paymentform.cpp プロジェクト: ButuzGOL/Halturka
PaymentForm::PaymentForm(QSqlRelationalTableModel *modelCome, int id,
                         QWidget *parent)
    : QDialog(parent),
    ui(new Ui::PaymentDialog)
{
    ui->setupUi(this);

    model = modelCome;

    QSqlTableModel *relModel = model->relationModel(Payment_Customer_id);
    ui->customerComboBox->setModel(relModel);
    ui->customerComboBox->setModelColumn(relModel->fieldIndex("surname"));

    relModel = model->relationModel(Payment_Work_id - 1);
    ui->workComboBox->setModel(relModel);
    ui->workComboBox->setModelColumn(relModel->fieldIndex("name"));

    ui->priceEdit->setValidator(new QIntValidator(0, 999999, this));

    mapper = new QDataWidgetMapper(this);
    mapper->setModel(model);
    mapper->addMapping(ui->customerComboBox, Payment_Customer_id);
    mapper->addMapping(ui->workComboBox, Payment_Work_id - 1);
    mapper->addMapping(ui->dateEdit, Payment_Date - 1);
    mapper->addMapping(ui->priceEdit, Payment_Price - 1);
    mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
    mapper->setItemDelegate(new QSqlRelationalDelegate(this));

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

    connect(ui->firstButton, SIGNAL(clicked()), mapper, SLOT(toFirst()));
    connect(ui->previousButton, SIGNAL(clicked()),
            mapper, SLOT(toPrevious()));
    connect(ui->nextButton, SIGNAL(clicked()), mapper, SLOT(toNext()));
    connect(ui->lastButton, SIGNAL(clicked()), mapper, SLOT(toLast()));
    connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addRecord()));
    connect(ui->deleteButton, SIGNAL(clicked()),
            this, SLOT(deleteRecord()));
    connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept()));
    connect(mapper, SIGNAL(currentIndexChanged(int)),
            this, SLOT(updateButtons(int)));
    connect(ui->workComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(updateFields(int)));

    if (id == -1) {
        ui->nextButton->setFocus();
    } else {
        ui->customerComboBox->setFocus();
    }
    int row = mapper->currentIndex();
    updateButtons(row);

    if (row == -1) {
        addRecord();
    }
}
コード例 #23
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();
}
コード例 #24
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;

};
コード例 #25
0
// Предоставление редактора
QWidget*  ComboBoxMailDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option,
        const QModelIndex& index) const
{

    if (index.column() == 1) {

        // 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());

            /* Удаление выбранных значений в кому */
            if (pole == tr("Кому")) {
                QString relFilter = QString("user_id != '00000000-0000-0000-0000-000000000000'");
                for (int i = 0; i < index.model()->rowCount(); i++) {

                    QString pole = index.model()->data(index.sibling(i, 0)).toString();

                    if (pole == tr("Кому") && index.row() != i) {
                        QString val = index.model()->data(index.sibling(i, 1)).toString();
                        if ( val != QString(""))
                            relFilter = QString("%1 and not user_id = '%2'").arg(relFilter).arg(val);
                    }
                    //QMessageBox::critical(0,"",index.model()->data(index.sibling(i,1)).toString());
                }
                //QMessageBox::critical(0,"","-"+relFilter+"-");
                relModel->setFilter(relFilter);
            }

            relModel->select();

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

            return pRes;

        }

        if (model->data(model->index(0, j)).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)).type() == QVariant::Bool) {
            QComboBox* pRes = new QComboBox(parent);

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


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

    if (index.column() == 0) {
        QComboBox* pRes = new QComboBox(parent);

        bool typeflag       = true;
        bool priorflag      = true;
        bool recipientflag  = true;
        bool beginflag  = true;
        bool endflag  = true;

        for (int i = 0; i < index.model()->rowCount(); i++) {

            QString pole = index.model()->data(index.sibling(i, 0)).toString();

            if (pole == tr("Тип") && index.row() != i)
                typeflag = false;
            if (pole == tr("Приоритет") && index.row() != i)
                priorflag = false;
            if (pole == tr("Начало") && index.row() != i)
                beginflag = false;
            if (pole == tr("Конец") && index.row() != i)
                endflag = false;
        }

        //if (recipientflag)
        pRes->addItem(tr("Кому"));

        if (typeflag)
            pRes->addItem(tr("Тип"));
        if (priorflag)
            pRes->addItem(tr("Приоритет"));
        if (beginflag)
            pRes->addItem(tr("Начало"));
        if (endflag)
            pRes->addItem(tr("Конец"));

        //pRes->addItem(tr("Копия"));

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

        return pRes;
    }


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

};
コード例 #26
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString data_path = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
    QDir data_dir;
    data_dir.mkpath(data_path);
    QString db_path = data_path + QDir::separator() + QString("assets.db");
    qDebug() << "DB path : " << db_path;

    db_helper = new DBHelper(db_path);
    QSqlError err = db_helper->initDb();
    if (err.type() != QSqlError::NoError) {
        showError(err);
        throw err;
    }

    market = new CryptocoinChartsMDP();
    updateCurrencies();

    model = new QSqlRelationalTableModel(ui->assetsTable);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setTable("assets");

    currency_column_index = model->fieldIndex("currency_id");
    quantity_index = model->fieldIndex("quantity");
    price_btc_index = model->fieldIndex("price_btc");
    mv_btc_index = model->fieldIndex("market_value_btc");
    price_usd_index = model->fieldIndex("price_usd");
    mv_usd_index = model->fieldIndex("market_value_usd");

    model->setRelation(currency_column_index, QSqlRelation("currencies", "id", "code"));

    model->setHeaderData(currency_column_index, Qt::Horizontal, tr("Currency"));
    model->setHeaderData(model->fieldIndex("quantity"), Qt::Horizontal, tr("Quantity"));
    model->setHeaderData(model->fieldIndex("price_btc"), Qt::Horizontal, tr("Price (BTC)"));
    model->setHeaderData(model->fieldIndex("market_value_btc"), Qt::Horizontal, tr("Market Value (BTC)"));
    model->setHeaderData(model->fieldIndex("price_usd"), Qt::Horizontal, tr("Price (USD)"));
    model->setHeaderData(model->fieldIndex("market_value_usd"), Qt::Horizontal, tr("Market Value (USD)"));

    if (!model->select()) {
        showError(model->lastError());
        return;
    }

    ui->assetsTable->setModel(model);
    ui->assetsTable->setItemDelegate(new QSqlRelationalDelegate(ui->assetsTable));
    ui->assetsTable->setColumnHidden(model->fieldIndex("id"), true);
    ui->assetsTable->setSelectionBehavior(QAbstractItemView::SelectRows);

    mapper = new QDataWidgetMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
    AssetEditDelegate *delegate = new AssetEditDelegate(this);
    mapper->setItemDelegate(delegate);
    mapper->setModel(model);
    mapper->addMapping(ui->quantityEdit, model->fieldIndex("quantity"));

    QSqlTableModel *relationModel = model->relationModel(currency_column_index);
    relationModel->sort(relationModel->fieldIndex("code"), Qt::AscendingOrder);
    ui->currencyComboBox->setModel(relationModel);
    ui->currencyComboBox->setModelColumn(relationModel->fieldIndex("code"));
    ui->currencyComboBox->installEventFilter(delegate);
    mapper->addMapping(ui->currencyComboBox, currency_column_index);

    connect(ui->assetsTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            mapper, SLOT(setCurrentModelIndex(QModelIndex)));

    connect(delegate, SIGNAL(dataChanged (const QModelIndex&)), this, SLOT(data_changed(QModelIndex)));

    ui->assetsTable->setCurrentIndex(model->index(0, 0));

    refreshMarketData(false);

    for (int c = 0; c < ui->assetsTable->horizontalHeader()->count(); ++c)
        ui->assetsTable->horizontalHeader()->setSectionResizeMode(c, QHeaderView::Stretch);

}
コード例 #27
-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;
}