Evgenii Legotckoi
Evgenii LegotckoiDec. 24, 2015, 10:27 a.m.

QML - Lesson 021. Switching between windows in QML

One of the articles had a chance to answer the question the reader how to implement switching between windows in Q t, so that when you change an inactive window hidden. At the touch of a button opens a second window, and the first closing. And switch back the same way.

Now we ask the same question, but with regard to QML. So, let's see how to implement it on the QML.

Project structre

  • question4.pro - profile project, the default is created and does not change;
  • main.cpp - the main source file, the default is created and does not change;
  • main.qml - qml main file to the main application window;
  • AnotherWindow.qml - type secondary windows project.

AnotherWindow.qml

Explanation of code begin with a secondary application window, since the transmission of information on the button is pressed to open the main application window is realized by a signal. And it is more convenient to describe this moment in the beginning, before proceeding to the main application code.


Signal syntax is as follows:

signal closeThisWindow

That is, the signal itself is declared and then comes its name. This same signal processor will be defined in the code as follows:

onCloseThisWindow: {
    // Some code
}

A signal is called as a function, as shown below in the following code a secondary window.

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Window 2.2

Window {
    id: anotherWindow
    signal signalExit   // Set signal
    width:480
    height:320

    // Button to open the main application window
    Button {
        text: qsTr("main window")
        width: 180
        height: 50
        anchors.centerIn: parent
        onClicked: {
            anotherWindow.signalExit() // invoke signal
        }
    }
}

main.qml

And in this file implemented the rest of the application logic. In the main window there are two buttons. In the handler of each button, the corresponding secondary window and the main window is hidden. While the handler clicking each window occurs secondary closure of the window and opening the main application window.

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1

ApplicationWindow {
    id: mainWindow
    visible: true
    width: 640
    height: 480
    title: qsTr("Switching between windows in QML")

    Rectangle {
        anchors.fill: parent
        color: "white"

        GridLayout {
            id: grid
            anchors.fill: parent

            rows: 2
            columns: 1

            Rectangle {
                Layout.fillHeight: true
                Layout.fillWidth: true
                Layout.column: 1
                Layout.row: 1

                // Button to open the first secondary application window
                Button {
                    text: qsTr("Первое окно")
                    anchors.centerIn: parent
                    width: 300
                    height: 50

                    onClicked: {
                        firstWindow.show()  // Open the first window
                        mainWindow.hide()   // Hide the main window
                    }
                }
            }

            Rectangle {
                Layout.fillHeight: true
                Layout.fillWidth: true
                Layout.column: 1
                Layout.row: 2

                // Button to open the second secondary application window
                Button {
                    text: qsTr("Второе окно")
                    anchors.centerIn: parent
                    width: 300
                    height: 50

                    onClicked: {
                        secondWindow.show() // Open a second window
                        mainWindow.hide()   // Hide the main window
                    }
                }
            }
        }
    }

    AnotherWindow {
        id: firstWindow
        title: qsTr("Первое окно")

        // The signal handler for the opening of the main window
        onSignalExit: {
            firstWindow.close()     // Close the first window
            mainWindow.show()       // Shows the main window
        }
    }

    AnotherWindow {
        id: secondWindow
        title: qsTr("Второе окно")

        // The signal handler for the opening of the main window
        onSignalExit: {
            secondWindow.close()    // We close the second window
            mainWindow.show()       // Shows the main window
        }
    }
}

Conclusion

The result will be implemented to switch between application windows has to QML, and thus you will always open only one application window.

Video

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Alex
  • Nov. 23, 2017, 3:17 p.m.

Спасибо за урок. Очень понравился. Подскажите если знаете сейчас везде системы управления автомобилей (выбор песни, навигатор, климат контроль (BMW, MERCEDES, etc))  делают с помощью Qt + Qml, там так же примерно сделан переход между окнами ?

Evgenii Legotckoi
  • Nov. 24, 2017, 4:13 a.m.

Нет. Там приложения работает в однооконном режиме, скорее всего в качестве базы используются объекты типа Rectangle, которые кастомизированы до состояния диалоговых окон. Также могут использоваться всякие StackView, SwipeView, Loader и т.д.


Хотя... Если там стоит полноценная Ubuntu с приложением в полноэкранном режиме, то вполне возможно наличие диалогов и окон, как в этой статье. Я могу только предполагать, как это работает, но у меня такие мысли на этот счёт.
a
  • Jan. 12, 2018, 2:45 a.m.

Добрый день! Подскажите пожалуйста. В учебных целях занимаюсь реализацией игры в шахматы, пока пишу игру для двух пользователей. Использую CPP + QML. Хочу сделать несколько окон. Главное окно с кнопками Игра и Просмотреть историю.

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

    Logic logic;
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("logic", &logic);
    engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));

    return app.exec();
}
В классе Logic у меня прописана логика фигур и обработка ходов. Отрисовка доски с фигурами реализована на QML. При нажатии кн. Игра хочу открывать окно с  QQmlApplicationEngine (так как реализовано у меня сейчас в однооконном режиме) и при закрытии окна с игрой возвращаться в главное окно. Вопрос в следующем: можно реализовать это с помощью QML или лучше создавать окна как описано https://evileg.com/post/112/ ?
Evgenii Legotckoi
  • Jan. 12, 2018, 3:03 a.m.

Добрый день!
Это всё можно реализовать средствами QML, однако я немного недопонимаю вашего вопроса в следующем отношении.
Вы хотите сделать это сохранив одноконный режим? (Что в рамках игры вполне логично, поскольку в большинстве случаев они делаются однооконными), или хотите повторить то, что сделано в этой статье?
В этой статье также используется только один QQmlApplicationEngine даже для двух окон, если ещё раз посмотрите статью, то можете обратить внимание на то, что там вызов окон осуществляется из файла main.qml.
Если хотите однооконный режим, то Вам может помочь Loader

Alex
  • Jan. 12, 2018, 3:13 a.m.
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    Logic logic;
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("logic", &logic);
    engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));

    return app.exec();
}

Добрый день, этот код не ваш, я видел этот код так как тоже его делал. Это задание для прохождения на собеседование в одну из крупных украинских IT компаний. Для переключения между окнами используйте Loader QML Type . И на будущее если используете чужой код, изменяйте его, так как не честно использовать чужое, или хотя бы указывайте что код не мой. Будут вопросы пишите.
a
  • Jan. 12, 2018, 4:13 a.m.

Все верно, я и не говорил что этот кусок кода лично мое произведение. Это тоже верно:

Это задание для прохождения на собеседование в одну из крупных украинских IT компаний.
Логику написал и уперся в окна. Я же не прошу написать за меня, хочу разобраться сам, спашиваю совета. Если кого обидел - прошу прощения. Спасибо огромное за совет.
Alex
  • Jan. 12, 2018, 4:16 a.m.

Ничего сложного, делаете по тех заданию 3 файла qml, называете их как указанно в тех задании, потом из первого окна через Loader их переключаете, в окне 2 и 3 делаете сигналы которые при закрытии формы вызывают первое окно, подключаете потом к ним логику. Готово.

a
  • Jan. 16, 2018, 7:40 a.m.

Спасибо всем. Все получилось. Прикручиваю логику.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 2:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
Mm
Mind minglesApril 12, 2024, 12:42 a.m.
ASO Service Forum: Enhancing App Visibility and Reach Welcome to the ASO Service Forum, your ultimate destination for insights, discussions, and strategies revolving around App Store Optimization. ASO (App Store Optimization) is paramoun…
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks