2016-12-17 68 views
1

我有這個項目使用QStatemachine來管理用戶界面,我想添加一個自定義列表。 UI應該只能由關鍵事件操縱。據我所知,我需要在qml端的ListView。如何使用QStatemachine來影響ListView?

ListView的委託僅對鼠標輸入或直接鍵輸入做出反應。但是我使用C++中的QStatemachine來操作它,因爲它正在處理UI的所有關鍵事件。 當我按下右箭頭鍵時,我想要發生的事情是將列表移動到左側。
(該CURRENTITEM常是在屏幕的中間。)

this is the inital State of the lisfview

enter image description here

所以我的ListView正在尋找這樣的時刻。

Component { 
      id:myDelegation 
      Item { 
       x: 50 
       width: 80 
       height: 60 
       Rectangle { 
        width: 60 
        height: 60 

        Text { 
        text: name 
        anchors.centerIn: parent 
        } 

        color: parent.ListView.isCurrentItem ? "red" : "steelblue"; 
        scale: parent.ListView.isCurrentItem ? 1.5 : 1; 
       } 

      } 
     } 


     ListView { 
      id: listView1 
      x: 0 
      y: 50 
      width: 1920 
      height: 214 
      orientation: ListView.Horizontal 
      spacing: 4 
      model: TileList{} 
      delegate: myDelegation 
      preferredHighlightBegin: width/2 - 10 
      preferredHighlightEnd: width/2 + 10 
      highlightRangeMode: ListView.StrictlyEnforceRange 
     } 

C++ Statemachine是一個將信號發送到qml的QStatemachine。

如何將信號綁定到Listview的委託?

+0

您可以直接從QML使用'StateMachine'。它比使用C++類更簡單快捷。 – dtech

+0

那麼我已經完成了在C++ Statemachine,它是相當大的。所以我不能從頭開始改變它。 – user1997675

+0

然後只是將其與QML連接。它已經是一個派生的QObject,因此您可以將其作爲上下文屬性公開並使用其信號和插槽。 – dtech

回答

1

步驟一 - 暴露的狀態機作爲上下文屬性,以便它是QML可見:

engine.rootContext()->setContextProperty("SM", stateMachinePtr); 

第二步 - 使用Connections元件以建立連接:

Connections { 
    target: SM 
    onSomeSignal: doSomeStuff() 
} 
+0

如果我使用QTQuickView而不是引擎,是否可以公開狀態機? – user1997675

+0

是的,'QQuickView'也有'rootContext()'。 – dtech

+0

好的。那麼我怎麼能夠使用onSignal來操縱listView?我不能只覆蓋'委託:'。我可以嗎? – user1997675

2

的最簡單的方法是隻讓狀態機設置「currentIndex」

一個常見的模式是有一個接口對象在QML和QState之間進行橋接機

class StateInterface : public QObject 
{ 
    Q_OBJECT 
    Q_PROPERTY(int currentIndex MEMBER m_currentIndex NOTIFY currentIndexChanged) 

public: 
    explicit StateInterface(QObject *parent = 0); 

signals: 
    void currentIndexChanged() const; 

private: 
    int m_currentIndex; 
}; 

該對象的一個​​實例被通過 「上下文屬性」 暴露於QML mechansism

StateInterface stateInterface; 
qmlEngine->rootContext()->setContextProperty("_stateInterface", &stateInterface); 

而在QML根據需要使用

ListView { 
    currentIndex: _stateInterface.currentIndex 
} 

QStateMachine使用相同stateInterface對象作爲國家財產分配的目標

QState *beginState = new QState(stateMachine); 
beginState->assignProperty(&stateInterface, "currentIndex", 0); 
// and so on. 

StateInterface對象還可以提供QML用於影響狀態更改的插槽。例如。

public slots: 
    void triggerReset() { emit trigger reset(); } 

signals: 
    void reset(); 

QStateMachine可以,例如,然後反應以第w的信號轉變的那些信號到beginState

總結此技術:

  1. QStateMachine控制應用狀態
  2. QML感興趣的所有狀態數據通過一個或多個接口對象公開
  3. QML端使用狀態數據以一種很好的聲明方式,就像它處理狀態一樣
相關問題