2017-08-16 102 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