How to merge/append/add two models for threading ?
Unsolved
General and Desktop
-
Hey Guys !!!
I am kinda newbie so if this post is in wrong place just inform me please.I am trying to use threads for "for loops" in my program but according to my research "model->setData" is not compatible with threading.
So my solutions is :
-> I am gonna use different models in each thread and at the and I am gonna merge them into one to show in tableview.But I am not familiar with qt so I kinda stuck here could you please check my code ?
t2 = std::thread{[&]{ for(unsigned int i = 0 ; i < ((RegexOperations_.indexed_arranged_file.size()+1) / 2) ; i++) { for(unsigned int j = 0 ; j < RegexOperations_.indexed_arranged_file[0].size();j++) { std::string temp = RegexOperations_.indexed_arranged_file[i][j]; QModelIndex index = model ->index(i,j,QModelIndex()); model->setData(index,temp.c_str()); } } } }; // t3 = std::thread{[&]{ // for(unsigned int i = ((RegexOperations_.indexed_arranged_file.size()+1) / 2) ; i < RegexOperations_.indexed_arranged_file.size();i++) // { // for(unsigned int j = 0 ; j < RegexOperations_.indexed_arranged_file[0].size();j++) // { // std::string temp = RegexOperations_.indexed_arranged_file[i][j]; // QModelIndex index = model ->index(i,j,QModelIndex()); // model->setData(index,temp.c_str()); // } // } // } // }; } t2.join(); //t3.join(); ui->tableView_results->setModel(model); ui->tableView_results->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tableView_results->setEditTriggers(QAbstractItemView::NoEditTriggers); }
Thank you for your help ...
-
Hi and welcome to devnet,
Why not use Qt's Signal and Slots ? That way you can have only one model that's updated by two threads.
-
The big question is: is the model flat? i.e. is it a list/table or a tree?
If so it's easy:
class ModelUpdateNotify : public QObject{ Q_OBJECT Q_DISABLE_COPY(ModelUpdateNotify) public: explicit ModelUpdateNotify(QObject* parent = Q_NULLPTR) : QObject(parent){} Q_SIGNAL void updateData(int row, int column, const QVariant& data); };
ModelUpdateNotify* notifier2 = new ModelUpdateNotify; QObject::connect(notifier2, &ModelUpdateNotify::updateData,model,[=](int row, int column, const QVariant& data){ model->setData(model ->index(i,j),data); },Qt::QueuedConnection); t2 = std::thread{[&,notifier2]{ for(unsigned int i = 0 ; i < ((RegexOperations_.indexed_arranged_file.size()+1) / 2) ; i++){ for(unsigned int j = 0 ; j < RegexOperations_.indexed_arranged_file[0].size();j++) notifier2->updateData(i,j,QString::fromStdString(RegexOperations_.indexed_arranged_file[i][j])); } delete notifier2; };