- 1. Project structre
- 2. AnotherWindow.qml
- 3. main.qml
- 4. Conclusion
- 5. Video
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.
Спасибо за урок. Очень понравился. Подскажите если знаете сейчас везде системы управления автомобилей (выбор песни, навигатор, климат контроль (BMW, MERCEDES, etc)) делают с помощью Qt + Qml, там так же примерно сделан переход между окнами ?
Нет. Там приложения работает в однооконном режиме, скорее всего в качестве базы используются объекты типа Rectangle, которые кастомизированы до состояния диалоговых окон. Также могут использоваться всякие StackView, SwipeView, Loader и т.д.
Добрый день! Подскажите пожалуйста. В учебных целях занимаюсь реализацией игры в шахматы, пока пишу игру для двух пользователей. Использую CPP + QML. Хочу сделать несколько окон. Главное окно с кнопками Игра и Просмотреть историю.
Добрый день!
Это всё можно реализовать средствами QML, однако я немного недопонимаю вашего вопроса в следующем отношении.
Вы хотите сделать это сохранив одноконный режим? (Что в рамках игры вполне логично, поскольку в большинстве случаев они делаются однооконными), или хотите повторить то, что сделано в этой статье?
В этой статье также используется только один QQmlApplicationEngine даже для двух окон, если ещё раз посмотрите статью, то можете обратить внимание на то, что там вызов окон осуществляется из файла main.qml.
Если хотите однооконный режим, то Вам может помочь Loader
Все верно, я и не говорил что этот кусок кода лично мое произведение. Это тоже верно:
Ничего сложного, делаете по тех заданию 3 файла qml, называете их как указанно в тех задании, потом из первого окна через Loader их переключаете, в окне 2 и 3 делаете сигналы которые при закрытии формы вызывают первое окно, подключаете потом к ним логику. Готово.
Спасибо всем. Все получилось. Прикручиваю логику.