2014-10-11 88 views
2

我開始用QML編寫應用程序(使用QtQuick 1.1和Qt 4.8.1),我有幾個關於信號的問題。在我的項目有以下文件:QML信號連接

main.qml:

Rectangle { 
    signal sigExit() 
    width: 800 
    height: 600 
    Text { 
     text: qsTr("Hello World") 
     anchors.centerIn: parent 
    } 
    MouseArea { 
     anchors.fill: parent 
     onClicked: { 
      sigExit(); 
      Qt.quit(); 
     } 
    } 
    Button 
    { 
     x: 10 
     y: parent.height-height-5 
     text: "someText" 
    } 
} 

Button.qml:

Rectangle { 
    signal buttonsig() 
    width: 60 
    //(...) 
    MouseArea 
    { 
     anchors.fill: parent 
     onClicked: buttonsig(); 
    } 
} 

當我想從信號連接main.qml到C++插槽,我做的:

main.cpp:

QmlApplicationViewer viewer; 
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto); 
viewer.setMainQmlFile(QLatin1String("qml/MyProject/main.qml")); 
viewer.showExpanded(); 

MyClass* obj = new MyClass; 
QObject* item = qobject_cast<QObject*>(viewer.rootObject()); 
QObject::connect(item, SIGNAL(sigExit()), obj, SLOT(onExitWindow())); 

它工作。但是當我想將sigbutton()Button.qml連接到C++插槽時怎麼辦?它會是這樣的?

QObject *rect = item->findChild<QObject*>("Button"); 
QObject::connect(rect, SIGNAL(buttonsig()), obj, SLOT(onExitWindow())); 

而第二個問題:我如何連接到sigbutton()main.qml(例如,我想他們點擊後,改變我的按鈕的位置)?

回答

1

您還需要有你Button項目的objectName財產,如果你想訪問:

Button { 
    id: myButton 
    objectName: "myButton" 
    x: 10 
    y: parent.height-height-5 
    text: "someText" 
} 

現在,您可以通過訪問:

QObject *rect = item->findChild<QObject*>("myButton"); 

關於第二個問題,您可以使用Connections對象將buttonsig()連接到main.qml中的某些QML信號處理程序:

Rectangle { 
    signal sigExit() 
    width: 800 
    height: 600 

    Connections{ 
     target: myButton 
     onButtonsig : 
     { 
      ... 
     } 
    } 

    Text { 
     text: qsTr("Hello World") 
     anchors.centerIn: parent 
    } 
    MouseArea { 
     anchors.fill: parent 
     onClicked: { 
      sigExit(); 
      Qt.quit(); 
     } 
    } 
    Button 
    { 
     id: myButton 

     x: 10 
     y: parent.height-height-5 
     text: "someText" 
    } 
} 

請注意,信號處理程序的名稱應該是on<Signal>(信號首字母大寫)。 Button也應該有一個id來解決它在Connections

+0

謝謝!那麼第二個問題呢?是否有可能將信號從一個QML文件連接到另一個QML文件中的插槽(或類似的東西)? – trivelt 2014-10-11 11:49:54

1

訪問已加載的qml元素,轉換它們並將它們的信號連接到C++插槽是非常可能的。但是在生產代碼中應該避免使用這種方法。 See this warning from Qt docs.

那麼從qml端調用C++插槽有什麼方法?您可以使用qml引擎將需要調用插槽的對象註冊爲上下文屬性。一旦註冊,這些上下文屬性就可以從QML的任何地方訪問。註冊爲背景屬性的對象

插槽可以直接在信號處理程序QML example: onClicked:{<contextPropertyName>.<slotName>()}

被稱爲或者,你可以連接與上下文屬性對象的插槽直接使用Connections類型QML信號。請參閱this documentation

有關注冊上下文屬性的詳細信息,請參閱Embedding C++ objects into QML with context properties.

如果你想看到一些例子,看看我這些問題的答案。 Qt Signals and Slots - nothing happensSetting object type property in QML from C++