Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change title of a QtQuick 2 window?

I am trying to change the default window of my project but it doesn't work. I am using QtQuick 2.0. Tried importing QtQuick.Window 2.0 and making Window{} as root object instead of Rectangle{} but it doesn't allow window objects as root.It gives me the following errors:

QQuickView only supports loading of root objects that derive from QQuickItem. 

If your example is using QML 2, (such as qmlscene) and the .qml file you 
loaded has 'import QtQuick 1.0' or 'import Qt 4.7', this error will occur. 

To load files with 'import QtQuick 1.0' or 'import Qt 4.7', use the 
QDeclarativeView class in the Qt Quick 1 module.

Any ideas on how to change the window title? I'm using Qt 5.1.1.

like image 519
adi Avatar asked Oct 03 '13 13:10

adi


1 Answers

This depends on how you want to use your GUI. If you want to use QML for almost everything, from window creation to the elements in your windows, the following solution may be the best option for you.

Qt5.1, only for desktop

If you have Qt5.1, you may use the new ApplicationWindow item from QtQuick.Controls as you root object in a file named main.qml:

import QtQuick 2.0
import QtQuick.Controls 1.0

ApplicationWindow {
    visible: true
    width: 360
    height: 360
    title: "MyWindow"

    Text {
        text: "Hello world!"
        anchors.centerIn: parent
    }
}

To avoid the error message you get, you need to start your application with a QQmlApplicationEngine instead of QQuickView. This may be done as follows in your main.cpp file:

#include <QtGui/QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{    
    QGuiApplication app(argc, argv);    
    QQmlApplicationEngine engine("main.qml");    
    return app.exec();
}

Qt5.0, (possibly) for environments other than desktop

If using Qt5.1 is not an option for you or you are targeting devices not yet supporting QtQuick.Controls, the alternative is to use Window in the following way. Add this to main.qml:

import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    visible: true
    width: 360
    height: 360
    title: "MyWindow"

    Text {
        text: "Hello world!"
        anchors.centerIn: parent
    }
}

And let this be your main.cpp:

#include <QtGui/QGuiApplication>
#include <QQmlEngine>
#include <QQmlComponent>

int main(int argc, char *argv[])
{    
    QGuiApplication app(argc, argv);    
    QQmlEngine engine;
    QQmlComponent component(&engine, QUrl::fromLocalFile("main.qml"));
    component.create();    
    return app.exec();
}

This should open a window with the text "Hello World!".

like image 166
dragly Avatar answered Sep 20 '22 07:09

dragly