Update combobox data



  • Re: Update combobox data from model

    I have no idea what happened but it just stopped working! Maybe because I've updated QT recently?

    Now the application crashes when I call QSqlTableModel select() method. I'm getting the following:

    The inferior stopped because it received a signal from the operating system.
    Signal name: SIGSEGV
    Signal meaning: Segmentation fault


  • Moderators

    @rudag I guess it crashes here?

    ((QSqlTableModel*)ui->comboBox->model())->select();
    

    As you can see you're dereferencing several pointers here. If one of them is invalid your app will crash with SIGSEGV. Does your combo box have a model? Does ui->comboBox point to a valid combo box instance? What does

    qDebug() << ui->comboBox->model();
    

    output?



  • @rudag
    If you're using ((QSqlTableModel*)ui->comboBox->model()), don't! Always use object_cast (or whatever it is) from Qt, and check the return result for NULL. There are so many posts here which fall foul of this....



  • @jsulm
    Yes and yes. It outputs: QSqlTableModel(0x20926780)

    @JonB
    I tried as you said:

    QSqlTableModel *mod = qobject_cast<QSqlTableModel *>(ui->comboBox->model());
    mod->select();
    

    And it's still crashing. I can call other methods like mod->tableName() and it works normal. I guess the problem is with the select() method. Using it is the only way I found to reload the combobox model. Is there any other way?


  • Moderators

    @rudag said in Update combobox data:

    QSqlTableModel *mod = qobject_cast<QSqlTableModel *>(ui->comboBox->model());
    mod->select();

    You forgot to check the pointer.



  • @jsulm
    The pointer is poiting correctly. Problem is with the method select().

    I'm trying to do this in another way now without using relation models.

    mapper->addMapping(ui->comboBox, model->fieldIndex("category"));
    ...
    void MainWindow::loadCategories()
    {
        ui->comboBox->clear();
    
        QSqlQuery q;
        int i = 1;
        q.exec("SELECT id, name FROM categories");
        while(q.next())
            ui->comboBox->insertItem(i++, q.value(1).toString(), q.value(0).toString());
    }
    

    My problem now is that it's not mapping the combobox data (insertItem() third argument). Am I missing something?


  • Lifetime Qt Champion

    Hi,

    Can you show the stack trace of your crash ?

    If the combo box is read-only, you might also want to consider a QSqlQueryModel.



  • @SGaist
    Eureka! It's working with QSqlQueryModel. I'm using setQuery() instead of select() and it's refreshing perfectly.

    By the way, QSqlQueryModel has no fieldIndex() method. Is there any similar method so I don't have to put the index static?


  • Lifetime Qt Champion

    You can get the QSqlRecord for your query and then use it to get what you want.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.