QML - Lesson 003. Custom Dialog in QML Android

custom dialog, dialog android, qml custom dialog, qml custom dialog example, qml dialog android, qt, qt android, qt qml dialog

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.
Support the author Donate
M

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

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Donate

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

DK
April 1, 2020, 8:03 a.m.
Dmitry Kozhinov

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

  • Result:40points,
  • Rating points-8
A
March 30, 2020, 12:47 p.m.
Anna

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

  • Result:60points,
  • Rating points-1
A
March 29, 2020, 12:14 p.m.
Alexanderv66

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

  • Result:71points,
  • Rating points1
Last comments
April 3, 2020, 8:06 a.m.
Konstantin Grudnitskiy

Я надеюсь вы уже разобрались в чем дело, но если вдруг нет, то проблема состоит в том, что вы пытаетесь запустить программу из интерпретатора питона. Файл main.py это уже готова…
April 3, 2020, 6:18 a.m.
Konstantin Grudnitskiy

>>> text = 'hello world'>>> ' '.join(word for word in text.split()[:-1])'hello'>>> def remove_last_word(text):... return text and ' '.join(word for word in text.s…
March 27, 2020, 2:40 p.m.
Evgenij Legotskoj

Добрый день. В конце пятой статьи скачать можете.
March 27, 2020, 2:28 p.m.
mkdir _

Здравствуйте, а можно, пожалуйста, ссылку на целые исходники, если есть?
March 27, 2020, 4:36 a.m.
Evgenij Legotskoj

Скорее всего также, как и для установки всех остальных переменых в CMake, через использование set
Now discuss on the forum
April 3, 2020, 12:53 p.m.
BlinCT

Само собою на компе этого незаметно.
April 3, 2020, 8:48 a.m.
Intruder

Евгений, добрый день. Спасибо!
s
April 3, 2020, 7:52 a.m.
solmik

да вроде много чего установленно, если неправильный путь указать то же самое, пробовал запустить видео через плей лист (по примерам из док)и из него назад путь взять, не получилось
April 3, 2020, 5:50 a.m.
Jurij-V

Спасибо ! Поковырявшись и посмотрев интерфейс QSvgRender и т.д. понимаю что похоже нужно будет лезть в реализацию ::render(..). Кто может подсказать как и где выкачать актуальные исходники…
April 2, 2020, 2:46 a.m.
Evgenij Legotskoj

Я думаю, что это где-то описано, но в такой глубине документации и максимум в самых базовых вещах, то есть отдельно в классах этого не пишут, просто потому, что придётся писать для каждого класс…
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB