Select Qt Combobox column

Asked

Viewed 59 times

0

I have a Connect button on the mainwindow.ui

void MainWindow::on_pushButton_clicked()
{
    ConectarDB = QSqlDatabase::addDatabase("QMYSQL");
    ConectarDB.setHostName("localhost");
    ConectarDB.setDatabaseName("Banco");
    ConectarDB.setPort(3306);
    ConectarDB.setUserName("root");
    ConectarDB.setPassword("root");}

It works perfectly, but I have two doubts:

1) As I would appear a message confirming that the connection was successfully performed, dps the button was clicked?

2) After connected, I have another form with a combobox on it.

Buscar_por_CURSO::Buscar_por_CURSO(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Buscar_por_CURSO)
{
    ui->setupUi(this);
    mBuscaCurso = new QSqlTableModel(this);
    mBuscaCurso->setTable("Cursos");
    mBuscaCurso->select();
    ui->comboBox->setModel(mBuscaCurso);
}

My table Courses:

Create table Cursos(
ID_curso int not null auto_increment,
Nome_curso varchar (50),
primary key (ID_curso)
)default charset = utf8;

That way, what appears on the combobox are the Id_curso, but I’d like it to be the Course name.

How do I fix it?

Grateful from now on

  • I ended up using QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("select nome_curso from Cursos"); ui->comboBox->setModel(model); to solve the second problem. But now I’m thinking of using the course name selected in the combobox to show in a tableview data from another table that has foreign key (Curso_id) references Cursos (ID_Curso). It’s possible to do that?

1 answer

0

To the problem 1:

void MainWindow::on_pushButton_clicked()
{
    ConectarDB = QSqlDatabase::addDatabase("QMYSQL");
    ConectarDB.setHostName("localhost");
    ConectarDB.setDatabaseName("Banco");
    ConectarDB.setPort(3306);
    ConectarDB.setUserName("root");
    ConectarDB.setPassword("root");
    **if (!ConectarDB.open()){
        QMessageBox::critical(this, "Error", ConectarDB.lastError().text());
        return;}
    else{
        QMessageBox msgBox;
        msgBox.setText("Conexão realizada com sucesso");
        msgBox.exec();}**
}

To the problem 2:

Buscar_por_CURSO::Buscar_por_CURSO(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Buscar_por_CURSO)
{
    ui->setupUi(this);
    QSqlQueryModel *model = new QSqlQueryModel;
    model->setQuery("select nome_curso from Cursos");
    ui->comboBox->setModel(model);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.