Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

QML - Lesson 002. Custom Button in QML Android

Android, qml, qml button, qml button android, qml custom button, qml custom button android, qt, qt qml

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

Virtual hosting with 10 percent discount
Virtual hosting with 10 percent discount
EVILEG offers reliable hosting with a 10% discount for virtual hosting and 5% for VPS

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

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
МБ
April 21, 2019, 9:40 a.m.
Моисей Бушуев

Qt - Test 001. Signals and slots

  • Result:0points,
  • Rating points-10
AA
April 17, 2019, 7:40 p.m.
Anton Ablin

Qt - Test 001. Signals and slots

  • Result:73points,
  • Rating points1
E
April 17, 2019, 6:16 p.m.
Evgeny

Qt - Test 001. Signals and slots

  • Result:100points,
  • Rating points10
Last comments
April 21, 2019, 4:22 p.m.
Евгений Легоцкой

Через метод setIcon table.horizontalHeaderItem(0).setIcon("qrc://path/to/icon.png")
April 21, 2019, 3:48 p.m.
Евгений Легоцкой

Добрый день! Спасибо за комментарий. Там действительно лучше будет сделать с инициализацией по умолчанию.
U
April 18, 2019, 3:37 p.m.
Unreal_man

А как иконку в хедер задать?
u
April 18, 2019, 2:15 a.m.
uaa

доброго времени,большое спасибо за пример для начинающего)при адаптации к своему проекту столкнулся с таким ньансом:в vepolyline.h в 47 строке нужна инициализация по умолчанию: int m_pointF...
E
April 11, 2019, 12:49 p.m.
Evgeny

Спасибо за ответ) У меня компоновщик на нее ругался просто. Оказалось, просто забыл Q_OBJECT в начале класса указать.
Now discuss on the forum
April 21, 2019, 4:16 p.m.
Евгений Легоцкой

Приветствую Нужно сохранять где-то выбранное значение, а потом восстанавливать его. Или использовать QSettings или добавить метод open(), в который передавать начальные значения для того...
R
April 19, 2019, 9:55 a.m.
RED_Spider

мені важко це зараз навіть перевірити, тому що знайшов коміт, це ще було в 2016 році, і цей код не буде працювати коректно зараз, єдине скажу що це були QThread
i
April 17, 2019, 3:03 p.m.
ilya.guzikov

BlinCT, на стороне ++ это делать необходимо так как в qml при использовании функции append происходит перерисовка всех точек лини(как я понимаю) и из-за этого при использовании больших массиво...
April 10, 2019, 11:20 a.m.
Алексей Внуков

может тоже кому надо будет - QML не принимает QVector<QVector<int>> , при попытке вывести полученый вектор QML показывает что это QVariant(QVector<QVector<int> ...
Join us in social networks

For registered users on the site there is a minimum amount of advertising