PDA

View Full Version : Mapping Table Model with QCombobox



Dr Ronald
9th March 2013, 20:00
So what I am trying to do it map data from a model to various widgets in a form (combo boxes, spin boxes, etc.). I would like the user to be able to change the index of one of the combo boxes (the "name" combo box) and have the rest of the widgets change accordingly. I am able to accomplish this with a table view by connecting the index of the mapper with the index of the table view; however, if I remove try to use the combo box as the primary means of changing the index, the index of the "name" combo box reverts to 0 as soon as I select another widget. Other than this, it seems to be working as it should. The other widgets in the form will also need to be used to edit the data. Any help is greatly appreciated. The following code is stripped down significantly.


ui->setupUi(this);

// Create the data model
model = new QSqlRelationalTableModel(ui->personList);
model->setEditStrategy(QSqlTableModel::OnFieldChange);
model->setTable("people");
model->setJoinMode(QSqlRelationalTableModel::LeftJoin);

// Remember the indexes of the columns
genderIdx = model->fieldIndex("gender");

// Set the relations to the other database tables
model->setRelation(genderIdx, QSqlRelation("gender", "genderid", "gender"));

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

//QSqlTableModel *relModel = model->relationModel(nameIdx);


// Set the model and hide the ID column
ui->personList->setModel(model);
ui->personList->setColumnHidden(0, true);
ui->personList->setSelectionMode(QAbstractItemView::SingleSelectio n);

// Initialize the Combo Boxes
ui->nameCBox->setModel(model);
ui->nameCBox->setModelColumn(model->fieldIndex("name"));

ui->genderCBox->setModel(model->relationModel(genderIdx));
ui->genderCBox->setModelColumn(model->relationModel(genderIdx)->fieldIndex("gender"));



//Create Mapper
QDataWidgetMapper *mapper = new QDataWidgetMapper(this);
mapper->setModel(model);
mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
mapper->addMapping(ui->nameCBox, model->fieldIndex("name"));
mapper->addMapping(ui->genderCBox, model->fieldIndex("gender"));


//************************************************** *******//

connect(ui->insertButton, SIGNAL(clicked()),
this, SLOT(insertPerson()));

connect(ui->nameCBox, SIGNAL(currentIndexChanged(int)),
mapper, SLOT(setCurrentIndex(int)));

connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteRow()));


ui->nameCBox->setCurrentIndex(0);
mapper->setCurrentIndex(0);