【发布时间】:2012-02-09 23:46:16
【问题描述】:
执行以下代码时, minimumSize 不考虑新添加的标签。在我的代码中显示窗口后添加标签,小部件应相应调整大小。如果我等待几毫秒(可能在第一次绘制之后),那么 minimumSize 是正确的,但我想在添加新标签后立即调整“w”的大小......
#include <QApplication>
#include <QtCore>
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <stdlib.h>
/* This application prints the following output:
label hint: 33x16
layout: 24x24
layout with label: 24x24
layout with label (activated): 24x24
And this comes out when the main_window->show() is executed last (this is correct):
label hint: 33x16
layout: 24x24
layout with label: 57x40
layout with label (activated): 57x40
*/
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget *main_window = new QWidget();
QWidget* w= new QWidget(main_window);
w->move(20,20);
QVBoxLayout *lay = new QVBoxLayout(w);
// When this happens *after* widgets are added, the sizes are OK.
// When we show the main window before, the sizes are wrong. Why ?
main_window->show();
QLabel *lbl = new QLabel("Hello");
QSize sz = lbl->sizeHint();
printf("label hint: %ix%i\n", sz.width(), sz.height());
sz = lay->minimumSize();
printf("layout: %ix%i\n", sz.width(), sz.height());
lay->addWidget(lbl);
// resizing 'w' here does not work because minimumSize is wrong...
// w->resize(lay->minimumSize());
sz = lay->minimumSize();
printf("layout with label: %ix%i\n", sz.width(), sz.height());
lay->activate();
sz = lay->minimumSize();
printf("layout with label (activated): %ix%i\n", sz.width(), sz.height());
// layout and label sizes are OK if this is executed here.
//main_window->show();
return app.exec();
}
在添加标签之前显示()时的主窗口:
http://lubyk.org/en/image394_std.png?661680336517
show() 最后出现时也是一样:
http://lubyk.org/en/image395_std.png?661680336526
真正的用例是某种“工具”小部件,在 lubyk 中显示网络上的远程进程。这些过程来来去去。如果我使用 QHBoxLayout 但里面的机器列表,它会使用所有垂直空间,这是一种浪费(而且丑陋)。通过有一个浮动小部件,它可以是透明的(看起来很漂亮),我们可以使用下面的空间。
进程出现时的Bug:
http://lubyk.org/en/image392_std.png?661680334428
正确的绘图(我调整了主窗口的大小以强制调整大小和大小更新):
http://lubyk.org/en/image393_std.png?661680334439
PS:“gaspard”是我机器的主机名。
【问题讨论】:
标签: qt