QThread operates QAbstractTableModel but no database, is it safe?
-
Hi,all.
I have a tableView , binded with a QAbstractTableModel, but NO database required.
The data will be caculated in a complicated way so it takes much time to be loaded.When caculating data in UI thread, the tableView will be stuck for a while.
So I move the caculating to a Qthread ,and in the thread :
{ // caculate things for(...){ caculate(); m_parent->m_tableModel->setItem(r,c,item); } // do other thing and finally set header: m_parent->m_tableModel->setHorizontalHeaderLabels(strListH); }
where m_parent is the UI class, and m_tableModel is QAbstractTableModel.
Under this operation ,the TableView does not be stuck again.But ,I wonder if this operation is safe under thread to call tableModel function?
If NOT SAFE, how to solve the UI stuck problem?
Thanks.
-
You must not access/modify ui elemtns from another thread than the main gui thread which you do when you add/remove/modify a model.
Use signals and slots to transfer the data from the worker thread to your model. -
@Christian-Ehrlicher
What if I first caculate and set tableModel in work Thread, then Bind tableModel in UI thread?Just Like:tableModel = new QStandardItemModel(row,col,this); waitThreadCaculateDone(); // fill tableModel data , with EventLoop so ui won't stuck tableView.bind(tableModel); // bind at the end