简体   繁体   English

从QML代码调用C ++函数

[英]Calling C++ function from QML code

I want to call a c++ function from my QML code. 我想从我的QML代码中调用c ++函数。

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. 例如,在下面的代码中我有一个带有2个输入的窗口:数量和价格我想调用一个c ++函数来评估小计并为其增加5%的税。

I have tried searching many places but couldn't get complete working code with this latest version of QT5. 我尝试过搜索很多地方,但无法使用最新版本的QT5获得完整的工作代码。 Please tell me how to call a C++ function from QML. 请告诉我如何从QML调用C ++函数。

main.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 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);
}

Simply use: 只需使用:

engine.rootContext()->setContextProperty("yourName", new yourClass());

In your qml you can call the function with yourname.yourfunction() Additional in your class you have to make your Function Q_INVOKABEL 在您的qml中,您可以使用yourname.yourfunction()调用该函数。在您的课程中,您必须使您的函数Q_INVOKABEL

You need to declare clickedButton as Q_INVOKABLE like this: 您需要将clickedButton声明为Q_INVOKABLE,如下所示:

 public:
 Q_INVOKABLE void cppMethod(const QString &msg) {
     qDebug() << "Called the C++ method with" << msg;
 }

See this sample: http://qt-project.org/doc/qt-4.8/qtbinding.html 请参阅此示例: http//qt-project.org/doc/qt-4.8/qtbinding.html

Create a class like : 创建一个类,如:

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;
};

in your main.cpp, include <QQmlContext> and modify as below 在你的main.cpp中,包含<QQmlContext>并修改如下

  QQmlApplicationEngine engine;
  engine.rootContext()->setContextProperty("billCalculator", new BillCalculator);
  engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

modify your main.qml file as below 修改你的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) : "____")
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM