2017-08-16 100 views
0

我想将一些参数从C++传递给QML,以便QML可以对它们做些什么。将参数从C++传递到QML

有点像这样:

void MyClass::myCplusplusFunction(int i, int j) 
{ 
    emit mySignal(i, j); 
} 

在QML,该mySignal(i, j)发出每一次,我想打电话给一个QML功能,做的东西与ij

Connections { 
    target: myClass 
    // mySignal(i, j) is emitted, call myQmlFunction(i,j) 
} 

我该怎么做呢?

+0

https://stackoverflow.com/questions/8834147/c-signal-to-qml-slot-in-qt –

+2

[C++ SIGNAL到Qt中的Qt槽]可能​​重复(https://stackoverflow.com/questions/8834147/c-signal-to-qml-slot-in-qt) – eyllanesc

+0

@ eyllanesc:这绝不是链接问题的副本。这只是相关的。在你链接的问题中,OP会尝试在C++端建立连接。这个问题是关于QML方面的连接。 – derM

回答

1

比方说,你在CPP侧的信号:

void yourSignal(int i, QString t) 

你有两个选择:

  • 将您的类注册为qml类型并将其用作qml对象。该对象将从QML端进行初始化。 reference

    qmlRegisterType<ClassNameCPP>("com.mycompany.qmlName", 1, 0, "ClassNameQml");

然后,在QML:

import QtQuick 2.9 
import com.mycompany.qmlName 1.0 

Item{ 
    ClassNameQml{ 
     id: myQmlClass 
     onYourSignal: { 
      console.log(i,t); // Do whatever in qml side 
     } 
    } 
} 
  • 添加类作为QML变量。当您需要重复使用您的对象多次时,此选项是首选。 reference

    view.rootContext()->setContextProperty("varName", &cppObject);

然后,在QML:

import QtQuick 2.9 
Item{ 
    Connections{ 
     target: varName 
     // In QML for each signal you have a handler in the form "onSignalName" 
     onYourSignal:{ 
      // the arguments passed are implicitly available, named as defined in the signal 
      // If you don't know the names, you can access them with "arguments[index]" 
      console.log(i,t); // Do whatever in qml side 
     } 
    } 
} 
+0

我添加了一些QML代码。我想这个答案正是Don Joe所要求的,它使用了两种可能的场景片段。 – albertTaberner

+0

现在你明白了,我想。 +1,尤其是我认为OP不太可能再次出现接受它。我在代码中添加了两条评论,并提供了一些更多的解释,我希望你对它有所了解。 – derM

0

你可以找到整个文档在这里:

http://doc.qt.io/qt-4.8/qtbinding.html

+0

谢谢你,感谢你 –

+1

由于链接可能会失效(特别是当你指向旧的Qt4.8文档时),如果你可以扩展答案的方式包含所有相关细节以回答题。链接应该只考虑*额外*。 – derM