Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML - main window position on start (screen center)

Tags:

c++

qt

qt-quick

qml

How I can do following: I’d like show my main window on start on the center screen.

like image 354
AntyaDev Avatar asked Jan 23 '12 11:01

AntyaDev


2 Answers

If using QtQuick, it's possible to do that:

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.0

ApplicationWindow {
    visible: true
    width: 320
    height: 480
    Component.onCompleted: {
        // Commenting this to use properties instead of setters
        //setX(Screen.width / 2 - width / 2);
        //setY(Screen.height / 2 - height / 2);
        x = Screen.width / 2 - width / 2
        y = Screen.height / 2 - height / 2
    }
}
like image 161
Dielson Sales Avatar answered Nov 15 '22 20:11

Dielson Sales


Dielson's answer is much better, especially since widgets weren't mentioned... anyway, here's an even simpler version of his answer:

import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    visible: true
    x: Screen.width / 2 - width / 2
    y: Screen.height / 2 - height / 2
    width: 320
    height: 480
}

As mentioned by Alexander, this binding can result in weird resizing behaviour. Because of that, it's better to use Dielson's answer. The only thing I'd mention is that it's not common to use setters in QML; some systems (I believe they're called property interceptors) even rely on properties being set to perform animations, for example. So the more common approach is as follows:

import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    visible: true
    width: 320
    height: 480

    Component.onCompleted: {
        x = Screen.width / 2 - width / 2
        y = Screen.height / 2 - height / 2
    }
}
like image 23
Mitch Avatar answered Nov 15 '22 21:11

Mitch