2017-07-13 26 views
-1

我有一个由JavaScript表达式(currentContainer)定义的属性:更改Qml中的JavaScript绑定事件?

Item { 
    id: theContainer 

    property alias currentIndex: theListView.currentIndex 
    signal onCurrentIndexChanged() 

    property MyCustomCppContainer currentContainer: { 
     if(theListView.currentIndex >= 0) 
      theModel.getCustomContainer(theListView.currentIndex) 
     else 
      null 
    } 
    signal onCurrentContainerChanged() // nobody calls this signal (yet) 

    MyCustomCppModel { 
     id: theModel 
    } 

    ListView { 
     id: theListView 

     anchors.fill: parent 

     model: theModel 
     currentIndex: -1 
     onCurrentIndexChanged: theContainer.onCurrentIndexChanged() 

     /* Other properties stripped for example */ 
    } 
} 

可悲的是我总是最后选定的容器,而不是当前所选择的一个:

ContainerItem { 
    onCurrentIndexChanged: { 
     //On first change, currentContainer is null 
     //though the first one was selected 

     //After selecting the second entry 
     //I get the result I expected last time 

     console.log(currentContainer.name); 
    } 
} 

我认为一个解决方案会有另一个信号currentContaineronCurrentContainerChanged()

但是谁称这个特殊信号?

+0

你对信号'onCurrentContainerChanged'(处理器:'onOnCurrentContainerChanged')和'onCurrentIndexChanged'(处理器'onOnCurrentIndexChanged')做了什么? – derM

+0

我想根据当前选择的项目修改交互式地图。地图本身是一个基于自定义QPainter的项目。它只支持添加和删除高亮显示的方法,所以我不能在这里简单地使用数据绑定。 –

+0

您是否尝试过在绑定中调试代码:'property MyCustomCppContainer currentContainer:[...]'with'console.log(...)' – derM

回答

0

我可以解决这个使用C++辅助类:

class PropertyChangedHelper : public QObject 
{ 
    Q_OBJECT 
    Q_PROPERTY(QVariant theProperty WRITE setTheProperty NOTIFY thePropertyChanged) 

public: 
    PropertyChangedHelper(QObject* parent = nullptr) : QObject(parent) {} 
    virtual ~PropertyChangedHelper() {} 

    void setTheProperty(QVariant) { 
     Q_EMIT thePropertyChanged(); 
    } 

Q_SIGNALS: 
    void thePropertyChanged(); 

private: 
    Q_DISABLE_COPY(PropertyChangedHelper) 
}; 

用法很简单:

PropertyChangedHelper { 
    theProperty: containerItem.currentContainer 
    onThePropertyChanged: { 
     console.log(containerItem.currentContainer.name); 
    } 
} 

我不知道这是否违反了任何设为Qml/QtQuick哲学,但它的作品。

+0

您可能会这样做,但您可以直接在QML中执行此操作 - 为什么? – derM

+0

也许你应该阅读:http://doc.qt.io/qt-5/qtqml-syntax-objectattributes.html#property-attributes - 对于你创建的每个属性,一个'[property] Changed''信号是隐含的创建。相应的处理程序一如既往:'在[Property] Changed'上 – derM

+0

啊我错过了! QtCreator没有正确自动完成,所以我认为没有信号。你用你的评论回答了我的问题! –