I want to call a c++ function from my QML code.
For example in the following code i have a window with 2 inputs : quantity and price I want to call a c++ function which evaluates the subtotal and adds 5% tax to it.
I have tried searching many places but couldn't get complete working code with this latest version of QT5. Please tell me how to call a C++ function from QML.
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();
}
}
}
Column{
Label {
text: qsTr("Enter the number of items purchased: ")
}
TextField {
id: in1
objectName: "in1"
}
Label {
text: qsTr("Enter the price per item ($):")
}
TextField {
id: in2
objectName: "in2"
}
Button {
id: button
objectName: "button"
text: "Compute"
onClicked: {
total.text = "Final bill, including 5% tax, is $" + clickedButton(in1.text, in2.text); // here i'm calling the c++ function
}
}
Label {
id: total
objectName: "total"
text: "Final bill, including 5% tax, is $____"
}
}
}
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
double clickedButton(int number, int price){
const double TAX_rate = 0.05;
double subtotal;
subtotal = price*number;
return (subtotal + subtotal*TAX_rate);
}