[Qt-interest] Centering the mainwindow

Stephen Jackson spjackson42 at gmail.com
Fri Feb 20 23:08:54 CET 2009


On Fri, Feb 20, 2009 at 9:05 PM, André Somers wrote:
>
>
> "Stephen Jackson" <spjackson42 at gmail.com> schreef in bericht
> news:43fef2450902190326t13dce301qd7a822165222ee32 at mail.gmail.com...
>> On Thu, Feb 19, 2009 at 9:04 AM, NARCISO, Rui wrote:
>>>
>>> Hi
>>> How do I make it so that my MainWindow appears centered in the screen
>>> like the QSplashScreen does?
>>>
>>> Rui
>>>
>>
>> Surely, if you look at the source of QSplashScreen you will find your
>> answer.
>
> It is actually not all that obvious. I checked, and I could not find it in
> there.
> So: some pointers for the TS then:
> QDesktopWidget has a lot of useful properties, including things like "QRect
> screenGeometry()". To center your window, you can use your window's
> setGeometry or move methods. Note however that these refer to the upper left
> point of your window. A bit of adding and dividing is needed to get where
> you want, but that should not be too hard.
>
> André
>

If I view qsplashscreen.cpp and search for "center", I find the
following code in the constructor.

    QRect r(0, 0, d->pixmap.size().width(), d->pixmap.size().height());
    resize(d->pixmap.size());
    move(QApplication::desktop()->screenGeometry().center() - r.center());

That is fairly obvious to me and is easily translated to the following
minimal example.

#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QMainWindow hello;

    hello.show();

    QRect r(0, 0, hello.width(), hello.height());
    hello.move(QApplication::desktop()->screenGeometry().center() - r.center());

    return app.exec();
}

This code centres a QMainWindow as I thought was required. I'm sorry
but I don't see why this isn't obvious to you, nor do I understand why
this does not answer the original poster's question.

I guess I must be overlooking something. Sorry.

Stephen Jackson




More information about the Qt-interest-old mailing list