执行以下代码时,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但机器列表里面,它使用所有垂直空间,这是一个浪费(和丑陋)。通过使用浮动小部件,它可以是透明的(看起来很漂亮),我们可以使用下面的空格。
进程出现时出现错误:
http://lubyk.org/en/image392_std.png?661680334428
正确绘图(我调整了主窗口的大小以强制调整大小和更改大小):
http://lubyk.org/en/image393_std.png?661680334439
PS:“gaspard”是我机器的主机名。
答案 0 :(得分:2)
尝试
lay->addWidget(lbl);
lbl->show();
main_window->update();
答案 1 :(得分:1)
QLabel
被认为不可见。如果在将标签添加到布局后添加lbl->setVisible(true)
,则尺寸相同。
那就是说,显示的显示效果仍然不太合适,但也许至少可以让你更近一步了?
此外,以下代码是否完成了您最终要实现的目标?
#include <QtGui>
class ToolWindow : public QDialog {
Q_OBJECT
public:
ToolWindow(QWidget *parent = NULL) : QDialog(parent, Qt::Tool) {
QVBoxLayout *layout = new QVBoxLayout;
setLayout(layout);
}
public slots:
void addButton() {
layout()->addWidget(new QPushButton("Hello, world"));
}
};
#include "main.moc"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QMainWindow main_window;
ToolWindow tool_window;
QPushButton *button = new QPushButton("Push Me!");
button->connect(button, SIGNAL(clicked()), &tool_window, SLOT(addButton()));
main_window.setCentralWidget(button);
main_window.show();
tool_window.show();
return app.exec();
}