【问题标题】:Qt QTreeWidget add items one by oneQt QTreeWidget 一一添加项目
【发布时间】:2013-03-04 02:23:30
【问题描述】:

这是我的代码

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 是一个函数,它的运行时间可能超过 2 秒。

我编译并运行了这个程序,没有任何错误或警告。

我想item会被treeWidget一一添加(添加了一项,2秒后会添加另一项。)

但是,当我运行它时,我发现所有Item 在漫长的等待之后都被添加了一次。为什么?

如何让那些items按照我的想法添加?

【问题讨论】:

    标签: c++ qt user-interface qtreewidget qtreewidgetitem


    【解决方案1】:

    您阻塞 GUI 线程的时间过长.. 理想情况下,您应该在另一个线程和 PingHost 中执行 PingHost,当结果可用时发送信号。然后你在主窗口中有一个 SLOT 来在收到信号时添加项目。

    如果你坚持做你现在正在做的事情,你可以尝试在每个循环结束时更新 treeWidget。见QWidget::update()

    【讨论】:

    • @midCat,那么您使用 Signal & SLOT 是徒劳的。您仍然阻止了 GUI 线程。尝试将其移动到另一个线程或使用 ui->treeWidget->update(); 刷新 treewidget;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多