Qt Quick How-tos

This page aims to provide an easily discoverable, useful reference that shows the simplest and best way of performing specific tasks in Qt Quick. Each solution provides QML and/or C++ code snippets where applicable, and every snippet is automatically tested by Qt to ensure they remain functional.

How do I:

Call a C++ function from QML when a Button is clicked

Assuming that the C++ type should be globally available to the QML files in the application, the simplest way is to make it a QML singleton with QML_SINGLETON. For example, in the header file, backend.h:

 #include <QObject>
 #include <QQmlEngine>

 class Backend : public QObject
 {
     Q_OBJECT
     QML_ELEMENT
     QML_SINGLETON

 public:
     Q_INVOKABLE void doStuff();
 };

backend.cpp:

 #include "backend.h"

 #include <QDebug>

 void Backend::doStuff()
 {
     qDebug() << "Did stuff!";
 }

You can then call that function from any QML file:

 import QtQuick.Controls

 import MyModule

 ApplicationWindow {
     width: 400
     height: 400
     title: qsTr("C++ Button example")

     Button {
         text: qsTr("Click me")
         onClicked: Backend.doStuff()
     }
 }

If the C++ type only needs to be available to a small set of QML files, consider using QML_ELEMENT. For more ways of exposing C++ types to QML, see Choosing the Correct Integration Method Between C++ and QML.

This example assumes that the Backend type is available in a QML module. With CMake, this is done via qt_add_qml_module. For an example that demonstrates this in detail, see Building a QML application.

See which item has active focus

Write a property change signal handler for the window's activeFocusItem property:

 import QtQuick
 import QtQuick.Controls

 ApplicationWindow {
     width: 400
     height: 400
     visible: true
     title: qsTr("Active focus debugging example")

     onActiveFocusItemChanged: print("activeFocusItem: " + activeFocusItem)

     Row {
         TextField {
             objectName: "textField1"
         }
         TextField {
             objectName: "textField2"
         }
     }
 }

This will print the item which currently has active focus to the console. To ensure that the output is useful, give each item a descriptive objectName.