Evgenii Legotckoi
Evgenii LegotckoiOct. 12, 2015, 11:15 a.m.

QML - Lesson 002. Custom Button in QML Android

I will begin a series of lessons on QML Android to customize a button, or better to say with styling, as in this case the term is more appropriate. We will not invoke the dialog boxes in this tutorial, but just do your QML Cutom Button , which will change color when you click on it. And there will be two for clarity, these buttons.

The first button will be red with a black border and black text, and when pressed, it will change the background color to black with red border and red text. The second button will have the same colors, but in the opposite sequence.

Project structure of QML Custom Button

The project is created in QtCreator as the application project with Qt Quick Quick Controls elements. In fact, there already is menyubar, multiple conversations and a couple of buttons. So, throw out all but two buttons and go to customize them.

And the structure of the project, in this case get the following:

  • QMLCutomButton.pro - project profile;
  • deployment.pri - deployment profile;
  • main.cpp - source file with main function;
  • qml.qrc - resource file for images, qml files and so on;
  • main.qml - main qml file;
  • MainForm.ui.qml - resource qml file for using with qml designer

QMLCustomButton.pro

TEMPLATE = app

QT += qml quick widgets

SOURCES += main.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)

deployment.pri

unix:!android {
    isEmpty(target.path) {
        qnx {
            target.path = /tmp/$${TARGET}/bin
        } else {
            target.path = /opt/$${TARGET}/bin
        }
        export(target.path)
    }
    INSTALLS += target
}

export(INSTALLS)

main.cpp

In thie file you have to create QML engine and load main.qml file.

#include <QApplication>
#include <QQmlApplicationEngine>

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

    QQmlApplicationEngine engine; // Create qml engine
    // And load main.qml file
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

MainForm.ui.qml

QtCreator warns that the file can only be edited in the designer, but in fact it is not. But we will not edit it manually.

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.2

Item {
    width: 640
    height: 480

    // Specify the name of the button to access them
    property alias button1: button1
    property alias button2: button2

    // Layer with buttons
    RowLayout {
        anchors.centerIn: parent

        // The first button
        Button {
            id: button1
        }

        // The second button
        Button {
            id: button2
        }
    }
}

main.qml

And now look the logic operation buttons, which was described at the beginning of this article. For styling buttons used setting style, which defines ButtonStyle. The Body of Custom Button  is a rectangle Rectangle, acting as the background of a button. For this Rectangle we will set the color and stroke with rounded corners. And to customize the text, you must override the Button Style button label, specifying the text color.

Note also that the color designation is made through a conditional expression by checking the object control, which points to the widget, ie the button that controls the style. If this control is pressed, the color of one another otherwise.

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4

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

    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 black border with rounded edges,
                 * otherwise, it will be black with a red border
                 */
                color: control.pressed ? "red" : "black"
                border.color: control.pressed ? "black" : "red"
                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: control.pressed ? "black" : "red"
            }
        }

        // Styling second button
        button2.style: ButtonStyle {
            // Styling the appearance of button
            background: Rectangle {
                color: control.pressed ? "black" : "red"
                border.color: control.pressed ? "red" : "black"
                border.width: 2
                radius: 5
            }
            // Styling button color
            label: Text {
                text: qsTr("Press Me 2")
                color: control.pressed ? "red" : "black"
            }
        }
    }
}

Result

Definitely, I am pleased that it is possible without any emulators and installation on Android Device to see the result of this work, and it is very inspiring. Yes, cross-platform and can not but rejoice.

And the appearance of the resulting keys will be such as shown below for screenshots and desktop with Meizu M1 Note smartphone. Also, look at the application logic can work in a video tutorial that comes after screenshots.

QML Custom Button on Desktop

QML Custom Button on Android

QML Custom Button on Android - pressed left button

QML Custom Button on Android pressed right button

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!

alex_lip
  • Nov. 17, 2017, 5:37 a.m.

А как кастомайзить Button если использовать QtQuick.Controls 2.0 ? В этом случае пишет Cannot assign to non-existent property "style"

alex_lip
  • Nov. 17, 2017, 6:04 a.m.

Нашел
http://doc.qt.io/Qt-5/qtquickcontrols2-customize.html#customizing-button

U
  • May 3, 2019, 11:14 p.m.
  • (edited)

Делаю вроде правильно, а ничего не получается. Что упустил? После button1. в выпадающем списке нет style.
Да, и откуда в уроке взялся файл .pri и зачем он нужен?

Evgenii Legotckoi
  • May 6, 2019, 2:39 a.m.

Добрый день. Этот урок для Qt Quick Control версии 1, Вы используете вторую версию. Здесь style уже нет, кастомизацию можно делать уже или черещ соответствующие property или через contentItem , или через делегаты, в зависимости от типа кастомизируемого объекта. Нужно отталкиваться от документации на конкретный объект

ЕВ
  • Nov. 8, 2019, 7:18 a.m.

Добрый день. Не могу найти ссылки на скачивание проекта.

Добрый день. Её здесь нет.

Будьте добры, выложите проект-пример. QT быстро эволюционирует, сейчас уже 5.13 версия. В вашем проекте версия 5.5 и много отличий. Очень тормозится изучение.

Стараюсь ничего не обещать в этом направлении, ибо много основной работы и тем более, как вы и сказали - Qt очень быстро эволюционирует, но постараюсь обновить эту статью на выходных для Qt Quick 2

Evgenii Legotckoi
  • Nov. 9, 2019, 2:50 a.m.
  • (edited)

Как и обещал, вы можете посмотреть новую статью QML - Урок 037. Кастомизация кнопок в QML (Обновление урока 002) . Там же найдёте ссылку на Git репозиторий. Не забудьте поставить звёздочку репозиторию )))

ac
  • Dec. 27, 2020, 4:09 a.m.

А есть ли первый урок в серии QML ?

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 с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks