Evgenii Legotckoi
Nov. 9, 2019, 1:42 p.m.

QML - Tutorial 037. Customizing Buttons in QML (Update Lesson 002)

At the request of one of the users, I am updating one of the first lessons in accordance with the current status of Qt. Namely, a new lesson will be written using Qt Quick Controls 2.

Namely, we customize the appearance of our application so that the buttons look as follows.


Introduction

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

Versioning

  • Qt 5.13
  • Qt Quick Controls 2

Project structure

I will not delve into the contents of the pro file, since it is created by default. But all the other files we will study.

main.cpp

I can say that the contents of the templates for the main.cpp file have undergone significant changes. And now the default file created is as follows.

  1. #include <QGuiApplication>
  2. #include <QQmlApplicationEngine>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6. QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  7.  
  8. QGuiApplication app(argc, argv);
  9.  
  10. QQmlApplicationEngine engine;
  11. const QUrl url(QStringLiteral("qrc:/main.qml"));
  12. QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
  13. &app, [url](QObject *obj, const QUrl &objUrl) {
  14. if (!obj && url == objUrl)
  15. QCoreApplication::exit(-1);
  16. }, Qt::QueuedConnection);
  17. engine.load(url);
  18.  
  19. return app.exec();
  20. }
  21.  

main.qml

Now create and customize our buttons.

  1. import QtQuick 2.12
  2. import QtQuick.Window 2.12
  3. import QtQuick.Controls 2.12
  4.  
  5. Window {
  6. visible: true
  7. width: 640
  8. height: 480
  9. title: qsTr("Custom Button")
  10.  
  11. // Create the first button
  12. Button {
  13. id: button_1 // Будем
  14. // Customize layout using anchors
  15. anchors.verticalCenter: parent.verticalCenter
  16. anchors.right: parent.horizontalCenter
  17. anchors.rightMargin: 15
  18. text: qsTr("Press me 1")
  19.  
  20. // To customize the text, you need to set the Text object to contentItem
  21. contentItem: Text {
  22. text: button_1.text
  23. color: button_1.pressed ? "black" : "red"
  24. }
  25.  
  26. // To customize the background, you must override the background property
  27.         // namely, install some object that inherits from Item
  28.         // For example Rectangle
  29. background: Rectangle {
  30. // The important point for dynamically setting the color is
  31.             // that we control the pressed property of the button we are interested in
  32.             // and depending on its state, set the color
  33. color: button_1.pressed ? "red" : "black" // as background color
  34. border.color: button_1.pressed ? "black" : "red" // so the borders
  35. border.width: 2
  36. radius: 5
  37. }
  38. }
  39.  
  40. // Similarly, we customize the second button
  41. Button {
  42. id: button_2
  43. anchors.verticalCenter: parent.verticalCenter
  44. anchors.left: parent.horizontalCenter
  45. anchors.leftMargin: 15
  46. text: qsTr("Press me 2")
  47.  
  48. contentItem: Text {
  49. text: button_2.text
  50. color: button_2.pressed ? "red" : "black"
  51. }
  52.  
  53. background: Rectangle {
  54. color: button_2.pressed ? "black" : "red"
  55. border.color: button_2.pressed ? "red" : "black"
  56. border.width: 2
  57. radius: 5
  58. }
  59. }
  60. }
  61.  

Conclusion

If you compare the previous article, you will see that the difference in code complexity is obvious. Personally, I consider it a good thing that now you do not need to redefine object styles for customization, as it was in Qt Quick Controls 1. It was an ugly and not flexible API for customization. And in some cases it was necessary to fix the private part of the code, which is also very bad. If you have to fix the private part of the code, then this says two things:

  • or errors, which can be corrected by contributing to the library code, and this is normal
  • or bad architecture, which is much worse

Also, this will be the first article, the code of which will be posted in a general special repository. I will try to put further articles in the repository on GitHub, that everything was in one place.

GitHub repository

Recommended articles on this topic

By article asked0question(s)

1

Do you like it? Share on social networks!

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