Qt Quick Como fazer
Esta página tem como objetivo fornecer uma referência útil e de fácil acesso que mostre a maneira mais simples e eficaz de realizar tarefas específicas no Qt Quick. Cada solução fornece trechos de código em QML e/ou C++, quando aplicável, e cada trecho é testado automaticamente pelo Qt para garantir que permaneça funcional.
Como faço para:
- Chamar uma função C++ a partir do QML quando um botão é clicado
- Verificar qual item está com o foco ativo
- Criar um seletor de hora semelhante ao TimePickerDialog do Android
- Usar uma enumeração do C++ no JavaScript
- Criar um Gauge
Chamar uma função em C++ a partir do QML quando um botão for clicado
Supondo que o tipo C++ deva estar disponível globalmente para os arquivos QML no aplicativo, a maneira mais simples é torná-lo um singleton QML com QML_SINGLETON. Por exemplo, no arquivo de cabeçalho, 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!";
}Você pode então chamar essa função a partir de qualquer arquivo QML:
import QtQuick.Controls
import MyModule
ApplicationWindow {
width: 400
height: 400
title: qsTr("C++ Button example")
Button {
text: qsTr("Click me")
onClicked: Backend.doStuff()
}
}Se o tipo C++ precisar estar disponível apenas para um pequeno conjunto de arquivos QML, considere usar ` QML_ELEMENT`. Para conhecer outras maneiras de expor tipos C++ ao QML, consulte Escolhendo o método correto de integração entre C++ e QML.
Este exemplo pressupõe que o tipo ` Backend ` esteja disponível em um módulo QML. Com o CMake, isso é feito por meio de ` qt_add_qml_module`. Para um exemplo que demonstre isso em detalhes, consulte “Compilando um aplicativo QML”.
Verificar qual item está com o foco ativo
Escreva um manipulador de sinal de alteração de propriedade para a propriedade ` activeFocusItem ` da janela:
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"
}
}
}Isso exibirá no console o item que está com o foco ativo no momento. Para garantir que a saída seja útil, atribua a cada item um valor descritivo para a propriedade ` objectName`.
Crie um seletor de hora semelhante ao TimePickerDialog do Android
Preparamos um exemplo que consiste em alguns arquivos QML que demonstram como fazer isso. Eles podem ser usados em seu aplicativo da seguinte maneira:
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls.Material
ApplicationWindow {
id: window
width: 600
height: 600
visible: true
title: qsTr("Time Picker Example")
Material.theme: darkThemeSwitch.checked ? Material.Dark : Material.Light
// Shows the selected time and opens the dialog.
TimeComponentLabel {
id: openDialogLabel
width: parent.width - 80
anchors.centerIn: parent
font.pixelSize: Qt.application.font.pixelSize * 8
renderTypeQuality: Text.VeryHighRenderTypeQuality
interactive: !timePickerDialog.opened
text: Qt.formatTime(new Date(1970, 1, 1, timePickerDialog.hours, timePickerDialog.minutes), "hh:mm")
onTapped: timePickerDialog.openWithMode(TimePicker.Mode.Hours)
}
ColumnLayout {
// We always want the openDialogLabel to be centered in the window, not us.
// For that reason, we use anchors rather than putting the root items into a ColumnLayout.
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: openDialogLabel.bottom
anchors.topMargin: 24
spacing: 12
Switch {
id: is24HourSwitch
text: qsTr("24 Hour")
checked: timePickerDialog.is24Hour
}
Switch {
id: darkThemeSwitch
text: qsTr("Dark")
}
}
TimePickerDialog {
id: timePickerDialog
anchors.centerIn: parent
is24Hour: is24HourSwitch.checked
onTimeAccepted: print("A time was chosen - do something here!")
}
}
TimePickerDialog em seu tema claro. |
TimePickerDialog no tema escuro. |
Usar uma enumeração do C++ no JavaScript
Para expor uma enumeração de C++ ao JavaScript (ou seja, ` QJSEngine`, e não ` QQmlEngine ` ou ` QQmlApplicationEngine`), use ` newQMetaObject()` e ` registerModule()`:
QJSEngine engine;
engine.installExtensions(QJSEngine::AllExtensions);
QJSValue metaObjects = engine.newObject();
const QJSValue backendJsMetaObject = engine.newQMetaObject(&Backend::staticMetaObject);
metaObjects.setProperty("Backend", backendJsMetaObject);
// Repeat the two lines above for other types as needed.
engine.registerModule("MyApp", metaObjects);
Backend backend(&engine);
const bool loaded = backend.load();A enumeração poderá então ser usada em JavaScript:
export function backendStatusUpdate(backendStatus) {
if (backendStatus === Backend.Error) {
console.warn("Error!")
return
}
console.log("Backend loaded successfully")
}Ao usar QQmlEngine ou QQmlApplicationEngine, existem opções mais simples; consulte “Escolhendo o método correto de integração entre C++ e QML” para obter mais informações.
backend.h:
#include <QObject>
#include <QJSEngine>
class Backend : public QObject
{
Q_OBJECT
public:
Backend(QJSEngine *engine);
enum Status {
Unknown,
Error,
Loading,
Loaded
};
Q_ENUM(Status)
bool load();
private:
QJSEngine *mEngine = nullptr;
};backend.cpp:
#include "backend.h"
Backend::Backend(QJSEngine*engine) :
mEngine(engine)
{
}
bool Backend::load()
{
// Faça algum carregamento aqui...
const QJSValue module = mEngine->importModule(":/script.mjs");
if (module.isError()) {
qWarning() << "Error loading script.mjs:" << module.toString();
return false;
}
const QJSValue function = module.property("backendStatusUpdate");
if (!function.isCallable()) {
qWarning() << "backendStatusUpdate script function is not callable!";
return false;
}
const QJSValue functionResult = function.call(QJSValueList() << Loaded);
if (functionResult.isError()) {
qWarning() << "backendStatusUpdate script function had errors:" << functionResult.toString();
return false;
}
return true;
}Para obter mais informações, consulte QObject Integration.
Criar um medidor
Preparamos um exemplo que consiste em alguns arquivos C++ e QML que demonstram como fazer isso. Eles podem ser usados em seu aplicativo da seguinte maneira:
import QtQuick.Controls
import GaugeHowTo
ApplicationWindow {
width: 400
height: 400
title: qsTr("Gauge example")
Gauge {
minimumValue: 0
value: 75
maximumValue: 100
}
}
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

