How can i use “kakkanna” in qml?
i cannot seem to get it working even after reading the docs since they seem to look a lot different.
I see nowhere anything like this what i’m trying to do…
when i click on the button, it will give me “qrc:///main.qml:32: ReferenceError: kusihousu is not defined”
i tried several methods like this in main.cpp:
engine.rootContext()->setContextProperty("kusihousu", kakkanna);
here is my code:
main.cpp:
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QObject>
#include "kakkanna.h"
int main(int argc, char *argv[])
{
Kakkanna* kannakka = new Kakkanna();
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
kakkanna.h:
#ifndef KAKKANNA_H
#define KAKKANNA_H
#include <QObject>
class Kakkanna : public QObject
{
Q_OBJECT
public:
explicit Kakkanna(QObject *parent = 0);
int value() const {return m_value;}
signals:
void valueChanged(int newValue);
public slots:
void setValue(int value);
void increment();
void decrement();
private:
int m_value;
};
#endif // KAKKANNA_H
kakkanna.cpp:
#include "kakkanna.h"
Kakkanna::Kakkanna(QObject *parent) :
QObject(parent)
{
m_value = 0;
}
void Kakkanna::setValue(int newValue)
{
if (newValue != m_value)
{
m_value = newValue;
emit valueChanged(newValue);
}
}
void Kakkanna::increment()
{
setValue(value()+1);
}
void Kakkanna::decrement()
{
setValue(value()-1);
}
main.qml:
import QtQuick 2.2
import QtQuick.Controls 1.1
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
menuBar: MenuBar {
Menu {
title: qsTr("File")
MenuItem {
text: qsTr("Exit")
onTriggered: Qt.quit();
}
}
}
Text {
text: qsTr("Hello World")
anchors.verticalCenterOffset: 1
anchors.horizontalCenterOffset: 0
anchors.centerIn: parent
}
Button {
id: button1
x: 185
y: 116
text: qsTr("Button")
onClicked: kusihousu.increment();
}
}
↧