Reputation: 523
I want my application to start maximized because the entire computer will be dedicated to that task, so I found the showMaximized()
function that fills that requirement, instead of the standard show()
. The problem is that I want my widgets to be ratiometric to the resulting useful size of the app window so that we can change hardware or window managers at some point in the future without touching the app at all.
The best way that I've found on my own to do it is as follows, but it relies on a race condition that usually works but sometimes causes the entire UI to be crammed into the top-left corner. Restarting the app fixes it, but I'd rather not have to tell the non-technical users to do that.
main.h:
#ifndef MAIN_H
#define MAIN_H
#include <QtWidgets>
class ResizeFilter : public QObject
{
Q_OBJECT
public:
ResizeFilter();
protected:
bool eventFilter(QObject* obj, QEvent* event);
signals:
void ResizeEvent(QSize size);
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
static MainWindow* GetInstance();
private:
static MainWindow* singleton;
MainWindow();
~MainWindow();
ResizeFilter* filter;
private slots:
void FinishInit(QSize size);
};
#endif // MAIN_H
main.cpp:
#include "main.h"
#include <QApplication>
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
MainWindow::GetInstance();
return app.exec();
}
ResizeFilter::ResizeFilter()
: QObject()
{
}
bool ResizeFilter::eventFilter(QObject* obj, QEvent* event)
{
if(event->type() == QEvent::Resize)
{
QResizeEvent* resizeEv = static_cast<QResizeEvent*>(event);
emit ResizeEvent(resizeEv->size());
}
return QObject::eventFilter(obj, event);
}
MainWindow* MainWindow::singleton = 0;
MainWindow* MainWindow::GetInstance()
{
if(singleton == 0)
{
singleton = new MainWindow();
}
return singleton;
}
MainWindow::MainWindow()
: QMainWindow(0)
{
filter = new ResizeFilter();
installEventFilter(filter);
showMaximized(); //do this before connecting so we miss the first resize event (wrong size) and catch the second (right size)
connect(filter, SIGNAL(ResizeEvent(QSize)), this, SLOT(FinishInit(QSize)));
}
void MainWindow::FinishInit(QSize size)
{
disconnect(filter, SIGNAL(ResizeEvent(QSize)), this, SLOT(FinishInit(QSize)));
delete filter;
filter = 0;
//build widgets based on size argument
}
MainWindow::~MainWindow()
{
}
I'm also open to a less rube-goldberg way of doing it. This looks a bit messy to me, but it's as compact as I think I can get it with my present knowledge.
(The singleton architecture is for another part of the project.)
Upvotes: 1
Views: 3264
Reputation: 2035
You can get the geometry and size of the screen using the DesktopWidget.
Upvotes: 2