Evgenii Legotckoi
Evgenii LegotckoiMarch 5, 2018, 3:13 a.m.

Android. Java vs Qt QML - Tutorial 000. Enable Material Design

When you develop both Java and Qt QML, you need to enable Material Design.

Material Design on Java

In the case of Java, it's enough to include the theme design in the styles.xml file and set the required color gamut for the application.

styles.xml

<resources>

    <style name="AppTheme" parent="android:Theme.Material">
        <!-- Main theme colors -->
        <!--   your app branding color for the app bar -->
        <item name="android:colorPrimary">@color/colorPrimary</item>
        <!--   darker variant for the status bar and contextual app bars -->
        <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
        <!--   theme UI controls like checkboxes and text fields -->
        <item name="android:colorAccent">@color/colorAccent</item>
    </style>

</resources>

colors.xml

Colors are specified in this file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

Material Design on Qt QML

In order to use Material Design on Qt QML, you must enable the use of Qt Quick Controls 2 in the project profile.

QT += quick quickcontrols2

Next, we connect the QQuickStyle class in main.cpp to use the static method of this class to include the Material Design style for the entire application.

#include <QGuiApplication>
#include <QQuickStyle> // Class to enabling styling
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQuickStyle::setStyle("Material"); // Enable Material Design

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

Changing the color scheme

To change the color style of the style, use the configuration file qtquickcontrols2.conf , which should be placed in the project root next to the project profile. You can add this file to resources to make it easier to work with this file from the IDE.

[Material]
Primary=#3F51B5
Accent=#FF4081
Theme=#303F9F
Foreground=#ffff00
Background=#00ffff

Color scheme settings

In Java, there are the following color scheme settings

  • colorPrimary - basic color, for example color Action Bar
  • colorPrimaryDark - color of the status bar
  • textColorPrimary - color of text for inscriptions on top of elements with a background colorPrimary
  • windowBackground - application background color
  • navigationBarColor - color of the phone's navigation menu
  • colorAccent - color of elements, such as checkboxes, etc.

Qt QML has only five color settings

  • Primary - basic color, elements similar to Action Bar
  • Accent - color elements such as checkboxes
  • Theme - color theme, applied to both the main application window as a background, and for pop-up menus or other other elements. Can also be overridden by Foreground and Background properties
  • Foreground - a separate color theme setting, can be applied to text, redefines the Theme settings.
  • Background - It is used to define the background of such elements as the menu, Navigation Drawer, etc. redefines the settings of Theme.

For Theme, you can use System as the value, which means using system color palettes. But you can do color correction with Foreground and Background.

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!

A
  • July 2, 2020, 5:05 p.m.

Подскажите пожалуйста, эта тема все еще актуальна? Или есть другие способы работать с темой? Вообщем хочу изменить цвет статус бара и бара навигации в приложении, но не знаю как это делать правильно. Можно сделать полный экран, но это кажется совсем не то...

Evgenii Legotckoi
  • July 3, 2020, 1:29 a.m.

Это актуально для изменения цвета. В файле qtquickcontrols2.conf переменная Primary должна влиять на цвет приложения соответственно и цвет ApplicationBar должен поменяться. Но у status bar вроде как нужно запускать код в Java потоке Android приложения.

Вот есть такое решение

QtAndroid::runOnAndroidThread([=]()
{
    QAndroidJniObject window = QtAndroid::androidActivity().callObjectMethod("getWindow", "()Landroid/view/Window;");
    window.callMethod<void>("addFlags", "(I)V", 0x80000000);
    window.callMethod<void>("clearFlags", "(I)V", 0x04000000);
    window.callMethod<void>("setStatusBarColor", "(I)V", 0xffffffff); // Desired statusbar color
});

Для изменения цвета текста

QAndroidJniObject decorView = window.callObjectMethod("getDecorView", "()Landroid/view/View;");
decorView.callMethod<void>("setSystemUiVisibility", "(I)V", 0x00002000);

Есть ещё вот такой репозиторий, который должен с этим работать github . Но насколько он актуален, я не знаю.
Но думаю, что лучше подключите проект из github в своём проекте. Он выглядит достаточно адекватным на беглый взгляд.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 24, 2024, 3:51 a.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 p.m.

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

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 p.m.

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

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 9, 2024, 7:43 a.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, 11:30 p.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, 9:38 p.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. 19, 2023, 10:01 a.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, 5:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 p.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, 6:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks