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

А как кастомайзить 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
МК
Jan. 13, 2019, 8:35 p.m.
Мария Канева

C++ - Test 005. Structures and Classes

  • Result:91points,
  • Rating points8
МК
Jan. 13, 2019, 8:32 p.m.
Мария Канева

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

  • Result:70points,
  • Rating points1
МК
Jan. 13, 2019, 8:28 p.m.
Мария Канева

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

  • Result:78points,
  • Rating points2
Last comments
I
Jan. 16, 2019, 8:06 a.m.
IscanderChe

Заработало. Забыл model->select(); вписать.
I
Jan. 16, 2019, 8:02 a.m.
IscanderChe

Всё равно пусто, хотя строка с данными в базу добавляется.
Jan. 16, 2019, 7:51 a.m.
Евгений Легоцкой

потому, что нужно сохранять информацию для всех остальных ролей и столбцов через вызов переопределённого метода. Да к тому же вы ещё и зациклили вызов метода data. QVariant MySqlTableModel:...
I
Jan. 16, 2019, 7:43 a.m.
IscanderChe

Сделал вот так. В tableView ничего нет, кроме заголовка. QVariant MySqlTableModel::data(const QModelIndex &index, int role) const{ if (role == Qt::DisplayRole) { QTime ...
Now discuss on the forum
Jan. 15, 2019, 4:53 p.m.
Михаиллл

Спасибо, заработало.Но выдало обычный текст без форатирования HTML.Придется искать дальше
Jan. 15, 2019, 12:52 p.m.
BlinCT

Я же вам выше написал CLion умеет работать с ремоут машинами. И Qt так же собирает.
ПБ
Jan. 14, 2019, 2:27 p.m.
Павел Богдевич

Да
m
Jan. 13, 2019, 4:52 p.m.
mihamuz

И так может кому будет интересно решил свою проблему следующим путем.Через дизайнер в базовый виджет добавил QQuickWidget (назвал его listProducts)Это соответственно убрал. this->m_qu...
Join us in social networks

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