gpt4 book ai didi

c++ - 如何在 QT 中逐步加载小部件?

转载 作者:行者123 更新时间:2023-11-30 02:01:30 25 4
gpt4 key购买 nike

我有一个自定义小部件,它在行中显示许多项目:

void update(){ //this is a SLOT which is connected to a button click
QVBoxLayout *layout = this->layout();
if (layout == NULL){
layout = new QVBoxLayout;
this->setLayout(layout);
} else {
QLayout_clear(layout); //this is a function that I wrote that deletes all of the items from a layout
}
ArrayList *results = generateData(); //this generates the data that I load from
for (int i = 0; i < results->count; i++){
layout->addWidget(new subWidget(results->array[i]));
}
}

问题是大约有 900 个项目,配置文件显示仅将子对象添加到布局需要 50% 的时间(构建需要另外 50%)。总体而言,加载所有项目大约需要 3 秒。

当我单击按钮加载更多数据时,整个 UI 会卡住 3 秒,然后所有项目都在完成后一起出现。有没有办法在创建项目时逐步加载更多项目?

最佳答案

正如 Pavel Zdenek 所说,第一个技巧是只处理部分结果。您希望同时处理尽可能多的内容,以便(我们将在下一步中执行的操作)开销较低,但您不想做任何会使系统看起来没有响应的事情。基于广泛的研究,Jakob Nielsen says that “0.1 秒是让用户感觉系统立即使用react的极限”,因此作为粗略估计,您应该将您的工作分成大约 0.05 秒的 block (再留出 0.05 秒让系统对用户的交互做出实际 react ).

第二个技巧是使用超时为 0 的 QTimer。作为 QTimer documentation说:

As a special case, a QTimer with a timeout of 0 will time out as soon as all the events in the window system's event queue have been processed. This can be used to do heavy work while providing a snappy user interface.

这意味着接下来将执行超时为 0 的计时器,除非事件队列中有其他内容(例如,鼠标单击)。这是代码:

void update() {
i = 0; // warning, this is causes a bug, see below
updateChunk();
}

void updateChunk() {
const int CHUNK_THRESHOLD = /* the number of things you can do before the user notices that you're doing something */;
for (; i < results->count() && i < CHUNK_THRESHOLD; i++) {
// add widget
}
// If there's more work to do, put it in the event queue.
if (i < results->count()) {
// This isn't true recursion, because this method will return before
// it is called again.
QTimer::singleShot(0, this, SLOT(updateChunk()));
}
}

最后,稍微测试一下,因为有一个陷阱:现在用户可以在循环的“中间”与系统交互。例如,用户可以在您仍在处理结果时单击更新按钮(这在上面的示例中意味着您会将索引重置为 0 并重新处理数组的第一个元素)。因此,更强大的解决方案是使用列表而不是数组,并在处理时将每个元素从列表的前面弹出。然后无论添加什么结果都会附加到列表中。

关于c++ - 如何在 QT 中逐步加载小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14043584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com