Home > database >  Transfer a list from a foreign key to an external combobox
Transfer a list from a foreign key to an external combobox

Time:01-20

Initially, I used qsqlrelationtablemodel in my database project. And the values were entered into the database using the combobox inside the tableView. And it looked something like this: enter image description here And the code looked very simple:

model->setTable(sql_query);
model->setRelation(1, QSqlRelation("my_schema.aircrafts","id_aircraft","registration_number"));
model->setRelation(3, QSqlRelation("my_schema.airports","id_airport","name_airport"));
model->setRelation(4, QSqlRelation("my_schema.airports","id_airport","name_airport"));       
ui->tableView->setModel(model);
ui->tableView->setItemDelegateForColumn(1, new QSqlRelationalDelegate(this));
ui->tableView->setItemDelegateForColumn(3, new QSqlRelationalDelegate(this));
ui->tableView->setItemDelegateForColumn(4, new QSqlRelationalDelegate(this));

But now I have redone the data entry on the forms and there are no problems with transferring information to qlineedit. There are difficulties with transferring data from foreign key's to an external combobox. Now it looks like this (the value of the combobox does not change when you click on another row of the tableView): enter image description here

Now I'm using this code, but I don't understand how to pass the value of the selected index in the tableView to the combobox.

        QString query = QString("SELECT * FROM my_schema.route WHERE id_route = '%1'").arg(id);
        QSqlQuery qw;
        qw.exec(query);
        while(qw.next())
        {
            ui->lineEdit->setText(qw.value(1).toString());
            ui->lineEdit_2->setText(qw.value(2).toString());
            ui->lineEdit_3->setText(qw.value(3).toString());
            ui->comboBox_2->setModel(model);
            ui->comboBox_2->setModelColumn(4);
        }

I would like to see something like this result: enter image description here Please tell me in the most accessible form how to achieve this

CodePudding user response:

You have model and tableview for fetching all columns for clicked row by using QAbstractItemView::clicked(const QModelIndex &index) signal for receive event. And implement the slot that loops all columns in selected row like this example snippet:

// create query with join for combobox model only containing desired values not foreign keys
// after that create QStringList and fill it with query result
// set stringlistmodel to combobox

ui->comboBox_2->setModel(stringlistmodel); // this is different from tableview's model

connect(ui->tableView, &QTableView::clicked, [this](const QModelIndex &index)
{
    auto row{index.row()};
    
    ui->lineEdit->setText(model.data(model.index(row, 0).toString());
    //...
    ui->comboBox_2->setCurrentIndex(model.data(model.index(row, 4).toInt());
    //...
});
  • Related