[英]QML - connect a signal from c++ to qml
我有一堆嵌套列表,鏈中最深的列表的高度為0。 因此,當用戶單擊一個按鈕時,該列表將展開。
我的問題是,我無法向列表的代表發出信號,以便它知道何時擴展。 而且我嘗試了很多東西。
我已經成功使用allready的一種方法使我失敗,因為它找不到正確的對象
view->setSource(QUrl(QStringLiteral("qrc:/content/CommentNumberDelegate.qml")));
QObject *obj3 = view->rootObject()->findChild<QObject*>("commentNumberDelegate");
QObject::connect(&gather, SIGNAL(showCommentsButtonClicked()), obj3, SIGNAL(showCommentsButtonClicked()));
這給了我錯誤:
QObject::connect: Cannot connect DataGather::showCommentsButtonClicked() to (null)::showCommentsButtonClicked()
是的,我已經正確設置了我正在訪問的文件的ObjectName屬性(CommentNumberDelegate.qml)。
CommentNumberDelegate.qml:小版本
Rectangle {
id: root
objectName: "commentNumberDelegate"
//width: parent.width + 20
height: 0 //col1.childrenRect.height //Screen.height * 0.1 //300 //col1.childrenRect.height
clip: true
property alias delegateState: root.state
signal showCommentsButtonClicked()
}
即使我以前已經成功連接了這樣的信號,也無法使它正常工作。 此代碼有效:
view->setSource(QUrl(QStringLiteral("qrc:/LoginPage.qml")));
QObject *obj = view->rootObject()->findChild<QObject*>("loginRectID");
QObject::connect(&gather, SIGNAL(loginSequenceFinished(QString)), obj, SIGNAL(loginSequenceFinished(QString)));
QObject *obj2 = view->rootObject()->findChild<QObject*>("mainRectID");
QObject::connect(&gather, SIGNAL(xmlFileCreationFinished()), obj, SIGNAL(xmlFileCreationFinished()));
當我使用調試器時,我可以看到QObject * obj3沒有正確分配,因為我無法訪問它。 在obj和ob2(工作代碼)上使用調試器時,我可以清楚地看到該對象已正確分配,因為在分配給對象之后,我可以使用調試器對其進行訪問。
我的問題是:我在這里可能做錯了什么?
我嘗試使對象失敗的任何方式,都保持為空。
因此,我嘗試查看在QML本身中,每次委托完成后該對象是否可用。 所以我做了:
delegate: CommentNumberDelegate {
objectName: "commentNumberDelegateID"
id: commentNumberDelegateID
Component.onCompleted: {
console.log("delegate completed = ", commentNumberDelegateID)
gatherer.test123(commentNumberDelegateID) // this function passes the address to c++
}
輸出:
qml: delegate completed = CommentNumberDelegate_QMLTYPE_2(0x2bfa5748, "commentNumberDelegateID")
qml: delegate completed = CommentNumberDelegate_QMLTYPE_2(0x2bf78d38, "commentNumberDelegateID")
因此,您可以看到組件完成時該對象確實可用。 所以我所做的就是將地址傳遞給一個名為test123的函數,該函數將QObject指針作為參數。
我曾經使用該指針將委托內部的信號連接到C ++中的信號
gatherer.h
class DataGather : public QObject
{
....
Q_INVOKABLE void showCommentsButton() { emit showCommentsButtonClicked(); }
Q_INVOKABLE void test123(QObject *obj);
....
signals:
void showCommentsButtonClicked();
}
gatherer.cpp
void DataGather::test123(QObject* obj)
{
QObject::connect(this, SIGNAL(showCommentsButtonClicked()), obj, SIGNAL(showCommentsButtonClicked()));
}
因此,基本上,您需要做的是:
從QML調用showcomments按鈕。 這將發出信號。 從QML您可以像這樣捕獲它:
commentNumberDelegate.qml:
Rectangle {
id: commentNumberDelegate
objectName: "commentNumberDelegate"
width: parent.width + 20
height: col1.childrenRect.height
clip: true
signal showCommentsButtonClicked()
onShowCommentsButtonClicked: console.log("showCommentsButtonClicked signal has been caught")
現在,我不確定這是否是正確的方法,但是它對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.