QtableView和模型在无限while循环中

问题描述 投票:0回答:2

我有一个QTableview,有一个模型附在它上面。我有一个无限的while循环,在该循环中我从服务器发送和接收消息。收到消息后,我想在表中添加一行。我的问题是我无法解决这个想法。当我执行while (true)时不起作用。如果有人可以帮助我,我将不胜感激。这是我正在谈论的代码:

model = new QStandardItemModel(4,1,this);
ui->tableView->setModel(model);
ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);

while (true)
{
    // Server response
    reciever_input.wait_for_recieve();

    std::vector<std::string> res = decode_msg(_serverResponse.front());

    unsigned int it;
    it = 8;

    if (res[0] == "Y")
    {
        int row = 0;
        //here I want to add rows in my table
        for (; it < res.size(); it++, row++)
        {
            std::string temp = res[it]; // this is the string that I want to add
            QString qtemp = QString::fromUtf8(temp.c_str());
            QModelIndex index = model->index(row,0,QModelIndex());
            model->setData(index,qtemp);
        }
    }
    if (res[0] == "L")
        break;
}
c++ qt view model
2个回答
0
投票

您是否尝试为服务器连接创建neu线程?我认为您应该在后台将其作为第二个线程运行,以防neu数据更新您的模型。

you can find qt doc here

您也可以在youtube中找到很好的例子


0
投票

您在insertRow()循环中缺少for。请通读文档here

我还没有亲自测试过代码,但是它看起来应该类似于下面的代码:

while (true)
{
    // Server response
    reciever_input.wait_for_recieve();

    std::vector<std::string> res = decode_msg(_serverResponse.front());

    unsigned int it;
    it = 8;

    if (res[0] == "Y")
    {
        int row = 0;
        //here I want to add rows in my table
        for (; it < res.size(); it++, row++)
        {
            std::string temp = res[it]; // this is the string that I want to add
            QString qtemp = QString::fromUtf8(temp.c_str());

            // insert row into the model 
            model->insertRow(row, new QStandardItem(qtemp));
        }
    }
    if (res[0] == "L")
        break;
    }
© www.soinside.com 2019 - 2024. All rights reserved.