euraad
euraad

Reputation: 2836

Why can't I update the QTableView model inside a thread automatically?

Introduction:

I'm using QT5 and I want to update a TableView where my model for the TableView is updated inside a thread.

*Method

I create a table like this and set it's columns and rows.

/* TableView */
    QStandardItemModel* looping_terminal_model = new QStandardItemModel(4, 2);
    looping_terminal_model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
    looping_terminal_model->setHeaderData(1, Qt::Horizontal, QObject::tr("DATA"));
    ui->looping_terminal_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->looping_terminal_tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->looping_terminal_tableView->setModel(looping_terminal_model);

Then I starting the thread.

    /* Threads */
    this->loop_terminal = new Loop_terminal(j1939, &start_loop_terminal_thread, looping_terminal_model);
    loop_terminal->start();

Inside the loop_terminal class, it looks like this

Loop_terminal::Loop_terminal(J1939* j1939, bool* start_loop_terminal_thread, QStandardItemModel* looping_terminal_model){
    this->j1939 = j1939;
    this->start_loop_terminal_thread = start_loop_terminal_thread;
    this->looping_terminal_model = looping_terminal_model;
    i = 0;
}

void Loop_terminal::run(){
    while(1){
        if(j1939->ID_and_data_is_updated){

            j1939->ID_and_data_is_updated = false;
        }
        QModelIndex index = looping_terminal_model->index(1,1,QModelIndex());
        // 0 for all data
        looping_terminal_model->setData(index,this->i);
        i++;
        msleep(1000);
    }
}

Result

The value can be shown in the blue cell. But it only updates if I click on the blue cell.

enter image description here

Discussion:

Here is the problem

 looping_terminal_model->setData(index,this->i);

Every time I updated an index, I need to press on the blue TableView cell, so it can updates. Or else, nothing happens. If I minimize the window, then it updates, but I can't see that.

What should I do, to make sure that the ui can update, even if it's outside of the thread?

Upvotes: 1

Views: 579

Answers (1)

eyllanesc
eyllanesc

Reputation: 243945

No, you cannot and should not. Models are intensively used by the view so they must live (and be modified) in the same thread as the view as they are not thread-safe. The solution is to send the information to the main thread using signals and there just update the model.

Upvotes: 3

Related Questions