简体   繁体   English

Qt QTreeWidget一一添加项

[英]Qt QTreeWidget add items one by one

this is my code 这是我的代码

QList<QString> IPs;  //IP address
...
connect(this, SIGNAL(addItems(QTreeWidgetItem*)), this, 
              SLOT(addNewItemToTree(QTreeWidgetItem*)));

void MainWindow::startPing()
{        
    for (int i = ipStart; i <= ipEnd; i++)
    {           
        QTreeWidgetItem *item = new QTreeWidgetItem();
        item->setText(0, IPs.at(i));
        if (PingHost(IPs.at(i)))
        {
            item->setText(1, "online");

        }
        else
        {
            item->setText(1, "offline");
        }
        emit addItems(item);
    }
}

void MainWindow::addNewItemToTree(QTreeWidgetItem *item)
{
    items.append(item);
    ui->treeWidget->addTopLevelItem(item);
}

PingHost is a function, It's run time maybe over 2 second. PingHost是一个函数,它的运行时间可能超过2秒。

I compiled and run this program whitout any error or warning. 我编译并运行了该程序,没有任何错误或警告。

I think item will be added to treeWidget one by one (one item is been added, after 2 second, another one will be added.) 我认为item将一个接一个地添加到treeWidget (添加一个项目,2秒后,将添加另一个。)

but, when I run it, I found all Item had been added one time after a long wait. 但是,当我运行它时,我发现经过长时间的等待,所有Item都已添加一次。 why? 为什么?

how to make those items added as my think? 如何使这些items成为我的想法?

You are blocking the GUI thread for too long.. Ideally, you should do PingHost in another thread and inside PingHost, you send a Signal when the result is available. 您阻塞GUI线程的时间太长了。 Then you have a SLOT in mainwindow to add the item when the signal is received. 然后,在主窗口中有一个SLOT,可在收到信号时添加该项目。

if you insist doing what you are doing now, you could try to update the treeWidget at the end of each loop. 如果您坚持要执行当前操作,则可以尝试在每个循环结束时更新treeWidget。 See QWidget::update() 参见QWidget :: update()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM