从QML代码调用C ++函数

时间:2014-10-16 08:14:41

标签: c++ qml qt5

我想从我的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);
}

3 个答案:

答案 0 :(得分:1)

只需使用:

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

在qml中,您可以使用yourname.yourfunction()调用该函数 您需要在课堂上添加功能Q_INVOKABEL

答案 1 :(得分:1)

您需要将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

答案 2 :(得分:1)

创建一个类:

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) : "____")
        }
相关问题