Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
QML and C++ bindings
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include "worker.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<Worker>("Worker.interface", 1, 0, "Worker");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
import QtQuick 2.3
import QtQuick.Controls 1.2
import Worker.interface 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Worker {
id: worker
}
menuBar: MenuBar {
Menu {
title: qsTr("File")
MenuItem {
text: qsTr("&Open")
onTriggered: console.log("Open action triggered");
}
MenuItem {
text: qsTr("Exit")
onTriggered: Qt.quit();
}
}
}
TextInput {
id: pWidth
x: 210
y: 118
width: 230
height: 43
text: qsTr("width")
font.pixelSize: 21
onEditingFinished: worker.calcHeight()
}
TextInput {
id: pHeight
x: 210
y: 193
width: 230
height: 47
text: qsTr("height")
font.pixelSize: 21
}
}
#include "worker.h"
Worker::Worker(QObject *parent) : QObject(parent)
{
}
float Worker::pixelWidth() {
return _pixelWidth;
}
void Worker::setPixelWidth(float value) {
_pixelWidth = value;
emit pixelWidthChanged();
}
float Worker::pixelHeight() {
return _pixelHeight;
}
void Worker::setPixelHeight(float value) {
_pixelHeight = value;
emit pixelHeightChanged();
}
void Worker::calcHeight() {
_pixelHeight = (_pixelWidth * 9) / 16;
emit pixelHeightChanged();
}
#ifndef WORKER_H
#define WORKER_H
#include <QObject>
class Worker : public QObject
{
Q_OBJECT
Q_PROPERTY(float pixelWidth READ pixelWidth WRITE setPixelWidth NOTIFY pixelWidthChanged)
Q_PROPERTY(float pixelHeight READ pixelHeight WRITE setPixelHeight NOTIFY pixelHeightChanged)
public:
explicit Worker(QObject *parent = 0);
float pixelWidth();
void setPixelWidth(float value);
float pixelHeight();
void setPixelHeight(float value);
Q_INVOKABLE void calcHeight();
signals:
void pixelWidthChanged();
void pixelHeightChanged();
public slots:
private:
float _pixelHeight;
float _pixelWidth;
};
#endif // WORKER_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment