如何在Qt中合并/追加/添加两个用于线程的模型?

How to merge/append/add two models for threading in Qt?

本文关键字:两个 用于 线程 模型 Qt 合并 添加 追加      更新时间:2023-10-16

我有点新手,所以如果这篇文章在错误的地方,请通知我。

我正在尝试在我的程序中使用线程进行"for 循环",但根据我的研究model->setData线程与线程不兼容。

所以我的解决方案是:
我将在每个线程中使用不同的模型,并且我将将它们合并为一个以显示在表格视图中。

但是我不熟悉Qt,所以我有点卡在这里,我不知道如何将两个模型相互合并,你能检查一下我的代码吗?

{
t2 = std::thread{[&]{
const auto row_size = (RegexOperations_.indexed_arranged_file.size()
const auto col_size = RegexOperations_.indexed_arranged_file[0].size();
for(unsigned int i = 0 ; i < (row_size+1) / 2)  ; i++)
{
for(unsigned int j = 0 ; j < col_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{[&]{
//    const auto row_size = (RegexOperations_.indexed_arranged_file.size()
//    const auto col_size = RegexOperations_.indexed_arranged_file[0].size();
//    for(unsigned int i = (row_size+1) / 2) ; i < row_size;i++)
//    {
//        for(unsigned int j = 0 ; j < col_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();
const auto tvr = ui->tableView_results;
tvr->setModel(model);
tvr->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
tvr->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

感谢您的帮助...

这是一种方法。

vector<std::string> answers;
std::mutex mx_answers;
auto rows = RegexOperations_.indexed_arranged_file.size();
auto cols = RegexOperations_.indexed_arranged_file[0].size();
answers.reserve(rows *cols);
auto answers_fill_it = answers.begin();
vector<std::thread> ts;
ts.reserve(rows);
auto rows = RegexOperations_.indexed_arranged_file.size();
for (row = 0; row < rows; ++row)
{
ts.emplace_back([&](
vector<std::string> local_answers;
local_answers.reserve(cols);
for (unsigned col = 0; col < cols; ++col) {
local_answers.push_back(RegexOperations_.indexed_arranged_file[row][col]);
};
lock_guard<std::mutex> lk(mx_answers);
std::copy(local_answers.begin(), local_answers.end(), answers_fill_it);));
}
auto answer_it = answers.begin();
for (auto t & : ts)
if (t.joinable())
t.join();
for (auto row = 0; row < rows; ++row)
for (auto col = 0; col < cols; ++col)
{
QModelIndex index = model->index(row, col, QModelIndex());
model->setData(index, *answer_it;
++answer_it;
}

它将其拆分为每行一个线程,并且随着每个线程的完成,它将该行的结果添加到字符串的全局向量中。

完成所有线程后,模型将更新。

相关文章: