Evgenii Legotckoi
Evgenii LegotckoiOct. 13, 2015, 11:37 a.m.

QML - Lesson 003. Custom Dialog in QML Android

Once we made customized buttons in the previous lesson , it is time to make the Custom Dialog, which will look more natively for Android devices, and can even look like the design on the IOS device. In any case, you will be able to more fully come to the realization of these devices guides.

To create a dialog object to be used Dialog of QtQuick.Dialog library. Nuance of A when working with custom dialog for Android is that the Standard Buttons that adequately look at the development of a desktop, for they look bad for Android, and more difficult to customize them for a beginner developer. The easiest way to implement your own buttons with their own stylization.

Development of Custom Dialog

Development of customized dialogue will continue on the basis of the project from the previous lesson. There we have two Custom Button have been created that we have a little tweak in color, so they looked concisely in relation to the dialogue. Also, using the technique in their styling, Styling dialog box button, which will be two buttons: "OK" and "Cancel". These buttons will close the dialog.

Dialog buttons will need to arrive at the bottom of the dialog, and the rest give a message "Hello, World !!!", as well as the section's button gray line with each other, and the same line will separate the buttons on the message. It will seem a bit on the IOS dialogue. As the line will be the Rectangle rectangle, the same technique is applied in the development of Android on Java, but instead of QML uses XML layout.

In order to make a customized normal contents of the dialog box, you must specify its parameter contentItem the object that will replace the contents. The most convenient is the Rectangle object, as early as it will place all other objects. Naturally no standard buttons there already and will not be in sight, so you can forget about them, but it is not a great loss indeed.


main.qml

All work will be carried out only in main.qml file, so just bring it. The rest of the information can see in the previous article .

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Dialogs 1.2
import QtQuick.Layouts 1.1

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    color: "white"

    MainForm {
        // Stretch the object of the main window over the parent element
        anchors.fill: parent

        // Styling the first button
        button1.style: ButtonStyle {
            // Styling the appearance of button
            background: Rectangle {
                /* If the button is pressed, it will be red 
                 * with a black bezel with rounded edges, 
                 * otherwise it will be black with a red rim
                 */
                color: control.pressed ? "#d7d7d7" : "#f7f7f7"
                border.color: "#d7d7d7"
                border.width: 2
                radius: 5
            }

            // Styling the button text color
            label: Text {
                /* If the button is pressed, the color will be black
                 * Otherwise red
                 */
                text: qsTr("Press Me 1")
                color: "black"
            }
        }

        // Styling second button
        button2.style: ButtonStyle {
            // Styling the appearance of buttons
            background: Rectangle {
                /* similarly as for the first button,
                 * But in the reverse order
                 */
                color: control.pressed ? "#d7d7d7" : "#f7f7f7"
                border.color: "#d7d7d7"
                border.width: 2
                radius: 5
            }
            // Styling button color
            label: Text {
                /* similarly as for the first button,
                 * But in the reverse order
                 */
                text: qsTr("Press Me 2")
                color: "black"
            }
        }

        // Start a dialogue by pressing any of the buttons in the main window
        button1.onClicked: dialogAndroid.open();
        button2.onClicked: dialogAndroid.open();

        // Create Object dialog box
        Dialog {
            id: dialogAndroid
            /* When deploite for Android-devices,
             * obligatory comment out these two lines,
             * another word glitches in the operation of the device
             */
            width: 600  // Set the width of the dialog, which works on the desktop, but it does not work on Android
            height: 500 // Set the height of the dialog, which works on the dekstop, but does not work on Android

            // Create the contents of the dialog box
            contentItem: Rectangle {
                width: 600          // Set the width, necessary for Android-devices
                height: 500         // Set the height, necessary for Android-devices
                color: "#f7f7f7"    // Set the color

                // The area for the dialog box message
                Rectangle {
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.top: parent.top
                    anchors.bottom: dividerHorizontal.top
                    color: "#f7f7f7"  // Задаём цвет области

                    Label {
                        id: textLabel
                        text: qsTr("Hello, World!!!")
                        color: "#34aadc"
                        anchors.centerIn: parent 
                    }
                }

                // Create a horizontal divider with the Rectangle
                Rectangle {
                    id: dividerHorizontal
                    color: "#d7d7d7"
                    height: 2 
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.bottom: row.top
                }

                /* Create a support for an object in the form of rows of buttons
                 * this facility for children objects do not work some parameters of
                 * anchors, except anchors.top parameters and anchors.bottom
                 */
                Row {
                    id: row
                    height: 100 // Set height
                    anchors.bottom: parent.bottom
                    anchors.left: parent.left
                    anchors.right: parent.right

                    Button {
                        id: dialogButtonCancel
                        anchors.top: parent.top
                        anchors.bottom: parent.bottom
                        // Set width button halfway line minus 1 pixel
                        width: parent.width / 2 - 1

                        style: ButtonStyle {
                            background: Rectangle {
                                color: control.pressed ? "#d7d7d7" : "#f7f7f7"
                                border.width: 0
                            }

                            label: Text {
                                text: qsTr("Cancel")
                                color: "#34aadc"
                                verticalAlignment: Text.AlignVCenter
                                horizontalAlignment: Text.AlignHCenter
                            }
                        }

                        onClicked: dialogAndroid.close()
                    }

                    Rectangle {
                        id: dividerVertical
                        width: 2
                        anchors.top: parent.top
                        anchors.bottom: parent.bottom
                        color: "#d7d7d7" // Задаём цвет разделителя
                    }

                    Button {
                        id: dialogButtonOk
                        anchors.top: parent.top
                        anchors.bottom: parent.bottom
                        width: parent.width / 2 - 1

                        // Стилизуем кнопку
                        style: ButtonStyle {
                            background: Rectangle {
                                color: control.pressed ? "#d7d7d7" : "#f7f7f7"
                                border.width: 0
                            }

                            label: Text {
                                text: qsTr("Ok")
                                color: "#34aadc"
                                verticalAlignment: Text.AlignVCenter
                                horizontalAlignment: Text.AlignHCenter
                            }
                        }
                        onClicked: dialogAndroid.close()
                    }
                }
            }
        }
    }
}

Result

As a result, you get Custom Dialog, which already will look decent on your Android device. Of course, under the dekstopov it will look awful, at least in this tutorial, but it is a question of the correct scaling size and configuration elements that are the issue of a separate article.

And here is the result of dialogue on my smartphone and the desktop you can see in the screenshots and in the video tutorial.

QML Custom Dialog Desctop

QML Custom Dialog Android

QML Custom Dialog Android

Video Lesson

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!

M
  • Oct. 4, 2017, 5:17 a.m.

Немного не понял
Заполнение Row происходит слава направо?
Сначала устанавливаем ButtonCancel потом Вертикальный разделитель и следом ButtonOk

Evgenii Legotckoi
  • Oct. 4, 2017, 6:42 a.m.

Ну да. Вас смущает последовательность? Можете и наоборот заполнить.
Это из разряда какой вариант юзабилити может быть удобнее. Начитался всяких гайдлайнов от Google да Apple, вот так и написал. А так дело вашего вкуса.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 1:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 1:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 1:35 a.m.

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

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 8, 2024, 3: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, 7: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, 5: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, 6: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
G
GarApril 22, 2024, 2:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 4:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 3:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 13, 2024, 11:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 1:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks