Evgenii Legotckoi
Oct. 12, 2015, 9:15 p.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

  1. TEMPLATE = app
  2.  
  3. QT += qml quick widgets
  4.  
  5. SOURCES += main.cpp
  6.  
  7. RESOURCES += qml.qrc
  8.  
  9. # Additional import path used to resolve QML modules in Qt Creator's code model
  10. QML_IMPORT_PATH =
  11.  
  12. # Default rules for deployment.
  13. include(deployment.pri)

deployment.pri

  1. unix:!android {
  2. isEmpty(target.path) {
  3. qnx {
  4. target.path = /tmp/$${TARGET}/bin
  5. } else {
  6. target.path = /opt/$${TARGET}/bin
  7. }
  8. export(target.path)
  9. }
  10. INSTALLS += target
  11. }
  12.  
  13. export(INSTALLS)

main.cpp

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

  1. #include <QApplication>
  2. #include <QQmlApplicationEngine>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6. QApplication app(argc, argv);
  7.  
  8. QQmlApplicationEngine engine; // Create qml engine
  9. // And load main.qml file
  10. engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
  11.  
  12. return app.exec();
  13. }

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.

  1. import QtQuick 2.5
  2. import QtQuick.Controls 1.4
  3. import QtQuick.Layouts 1.2
  4.  
  5. Item {
  6. width: 640
  7. height: 480
  8.  
  9. // Specify the name of the button to access them
  10. property alias button1: button1
  11. property alias button2: button2
  12.  
  13. // Layer with buttons
  14. RowLayout {
  15. anchors.centerIn: parent
  16.  
  17. // The first button
  18. Button {
  19. id: button1
  20. }
  21.  
  22. // The second button
  23. Button {
  24. id: button2
  25. }
  26. }
  27. }

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.

  1. import QtQuick 2.5
  2. import QtQuick.Controls 1.4
  3. import QtQuick.Controls.Styles 1.4
  4.  
  5. ApplicationWindow {
  6. visible: true
  7. width: 640
  8. height: 480
  9. title: qsTr("Hello World")
  10.  
  11. MainForm {
  12. // Stretch the object of the main window over the parent element
  13. anchors.fill: parent
  14.  
  15. // Styling the first button
  16. button1.style: ButtonStyle {
  17. // Styling the appearance of button
  18. background: Rectangle {
  19. /* If the button is pressed, it will be red
  20. * with black border with rounded edges,
  21. * otherwise, it will be black with a red border
  22. */
  23. color: control.pressed ? "red" : "black"
  24. border.color: control.pressed ? "black" : "red"
  25. border.width: 2
  26. radius: 5
  27.  
  28. }
  29.  
  30. // Styling the button text color
  31. label: Text {
  32. /* If the button is pressed, the color will be black
  33. * otherwise red
  34. */
  35. text: qsTr("Press Me 1")
  36. color: control.pressed ? "black" : "red"
  37. }
  38. }
  39.  
  40. // Styling second button
  41. button2.style: ButtonStyle {
  42. // Styling the appearance of button
  43. background: Rectangle {
  44. color: control.pressed ? "black" : "red"
  45. border.color: control.pressed ? "red" : "black"
  46. border.width: 2
  47. radius: 5
  48. }
  49. // Styling button color
  50. label: Text {
  51. text: qsTr("Press Me 2")
  52. color: control.pressed ? "red" : "black"
  53. }
  54. }
  55. }
  56. }

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

Do you like it? Share on social networks!

alex_lip
  • Nov. 17, 2017, 4:37 p.m.

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

alex_lip
  • Nov. 17, 2017, 5:04 p.m.

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

U
  • May 4, 2019, 9:14 a.m.
  • (edited)

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

Evgenii Legotckoi
  • May 6, 2019, 12:39 p.m.

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

ЕВ
  • Nov. 8, 2019, 6:18 p.m.

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

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

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

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

Evgenii Legotckoi
  • Nov. 9, 2019, 1:50 p.m.
  • (edited)

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

ac
  • Dec. 27, 2020, 3:09 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html