Qt:setGeometry不在应用程序的调整中调整大小
问题描述:
我正在为我的学位项目工作,并且我遇到了GUI问题。Qt:setGeometry不在应用程序的调整中调整大小
我已经测试了不同部件在独立项目上的位置以简化我尝试的代码。
这是我的问题: 我创建了一个超载的resizeEvent
来调整我的所有小部件。它工作的很好,除了一件事:
在我的测试程序启动后,窗口小部件尺寸不是很大,我需要手动调整窗口大小来强制重新调整窗口大小,即使setGeometry
调用位于构造函数就像下面的代码一样。
.H
MainWindow.h
-------------
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QGridLayout>
#include <QGroupBox>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void resizeEvent (QResizeEvent * event);
private:
Ui::MainWindow *ui;
QGroupBox *g1;
QGroupBox *g2;
QPushButton *but2;
QGridLayout *lay;
};
#endif // MAINWINDOW_H
的.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->lay = new QGridLayout();
this->g1 = new QGroupBox("g1");
this->g2 = new QGroupBox("g2");
this->but2 = new QPushButton("But2");
this->lay->addWidget(g1, 0, 0, 1, 1);
this->lay->addWidget(but2, 0, 1, 1, 1);
this->lay->addWidget(g2, 1, 0, 1, 2);
this->g1->setBaseSize(60, 60);
this->g2->setBaseSize(60, 60);
this->ui->centralWidget->setLayout(lay);
this->ui->centralWidget->setMinimumSize(100, 100);
this->but1->setHidden(true);
this->g1->setGeometry(5, 1, (this->ui->centralWidget->width())55, (this->ui->centralWidget->height())-83);
this->but2->setGeometry(this->g1->width()+10 , 6, 40, (this->ui->centralWidget->height())-88);
this->g2->setGeometry(5, this->g1->height()+5, (this->ui->centralWidget->width())-10, 70);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::resizeEvent (QResizeEvent * event)
{
this->g1->setGeometry(5, 1, (this->ui->centralWidget->width())-55, (this->ui->centralWidget->height())-89);
this->but2->setGeometry(this->g1->width()+10 , 6, 40, (this->ui->centralWidget->height())-88);
this->g2->setGeometry(5, this->g1->height()+5, (this->ui->centralWidget->width())-10, 70);
}
我试图找到一个解决方案,以使窗口小部件以及从一开始就大小
UPDATE这里有两张图片:
之前调整
调整后
的问题是,当里面有什么,该QGroupBox只取按钮的大小,在它旁边,我希望它从一开始就更大
答
而不是setGeometry
你应该对于其他部件时添加小部件布局(也许在resizeEvent()也行),喜欢...
int col = 0, row = 0;
int stretch = 100 * (this->ui->centralWidget->width()-55.0)/this->ui->centralWidget->width();
this->lay->setColumnStretch(col, stretch);
stretch = 100 * (this->ui->centralWidget->height())-89.0)/this->ui->centralWidget->height();
this->lay->setRowStretch(row, stretch);
同样的方式LD使用拉伸因素。
我强烈建议不要覆盖'resizeEvent',在整个大型项目中看到这一点,并导致各种问题。相反,尝试通过布局和间隔条来完成所需的外观,这通常是可能的,并且最终更平滑。如果您将包含初始和期望外观的屏幕截图,那么也可以有人帮助您。 – Bowdzone
我同意,但我不认为这里的问题是resizeevent,因为它调整我的窗口时,它工作得很好。我已经覆盖了它,因为我的不同布局的大小取决于它们中哪些隐藏或可见。我在这里遇到的问题是,在启动应用程序时,即使它是构造函数的结尾,setGeometry也不会执行。我试图在窗口中为QCoreApplication :: processEvent或widget.update添加一些行,但没有任何反应。 –
是的,但它仍然是一个XY问题。小部件的几何形状取决于其他小部件,这意味着在我可以想到调整大小之前,所有东西都必须绘制一次。所以我会找到另一种解决方法,让你不必头疼。 – Bowdzone