我想从QML代码中调用一个c++函数
例如,在下面的代码中,我有一个有2个输入的窗口:数量和价格我想调用一个c++函数来评估小计并向其添加5%的税。
我试过搜索很多地方,但无法获得最新版本的QT5的完整工作代码。请告诉我如何从QML调用C++函数。
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);
}
创建一个类,如:
class BillCalculator : public QObject
{
Q_OBJECT
Q_PROPERTY(double totalPrice READ totalPrice WRITE setTotalPrice NOTIFY totalPriceChanged)
public:
BillCalculator(QObject *parent = 0) :
QObject(parent),
mTotalPrice(0.0)
{
}
double totalPrice() const { return mTotalPrice; }
signals:
void totalPriceChanged();
public slots:
void setTotalPrice(const double &arg)
{
if(mTotalPrice != arg)
{
mTotalPrice = arg;
emit totalPriceChanged();
}
}
void calculateTotalPrice(int number, int price)
{
const double TAX_rate = 0.05;
double subtotal;
subtotal = price*number;
setTotalPrice(subtotal + subtotal*TAX_rate);
}
protected:
double mTotalPrice;
};
在你的main.cpp中,包括<QQmlContext>
并修改如下
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("billCalculator", new BillCalculator);
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
修改你的main.qml文件如下
Button {
id: button
objectName: "button"
text: "Compute"
onClicked: {
billCalculator.calculateTotalPrice(parseInt(in1.text), parseInt(in2.text));
}
}
Label {
id: total
objectName: "total"
text: "Final bill, including 5% tax, is $" + (billCalculator.totalPrice > 0 ? billCalculator.totalPrice.toFixed(2) : "____")
}
您需要将clickedButton声明为Q_INVOKABLE,如下所示:
public:
Q_INVOKABLE void cppMethod(const QString &msg) {
qDebug() << "Called the C++ method with" << msg;
}
请参阅此示例:http://qt-project.org/doc/qt-4.8/qtbinding.html
简单使用:
engine.rootContext()->setContextProperty("yourName", new yourClass());
在qml中,您可以使用yourname.yourfunction()
调用函数另外,在您的类中,您必须使函数Q_INVOKABEL