QT / QML业务逻辑与UI分离

时间:2017-11-05 17:55:29

标签: qt qml qt-signals

我试图将业务逻辑放在Main.qml中,将用户界面放在MainForm.ui.qml中,但我无法通过窗口小部件ID进行连接。

MainForm.ui.qml:

import QtQuick 2.8
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3

Page {
   id: page
   header: TabBar { ... }
   StackLayout {
      id: stack
      Pane {
         Flow {
            TextField {
               id: theText
            }
            property alias sendBtn: sendBtn
            Button {
               id: sendBtn
            }
         }
      }
   }
}

Main.qml:

import QtQuick 2.8
import QtQuick.Window 2.2

Window {
   visible: true
   width: 640
   height: 480
   title: qsTr("Hello World")
   MainForm {
      anchors.fill: parent
      sendBtn {
         onClicked: backend.sendTextToServer( theText.text )
      }
   }
}

Qt Creator说:Invalid property name "sendBtn" (M16)

运行失败并显示以下消息:

QQmlApplicationEngine failed to load component
qrc:/Main.qml:12 Cannot assign to non-existent property "sendBtn"

1 个答案:

答案 0 :(得分:1)

当您将property alias sendBtn: sendBtn放入Pane时被解释为Pane属性,因此您无法以这种方式访问​​它,将它放在Page的上下文中是正确的。

import QtQuick 2.8
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3

Page {
   id: page
   property alias sendBtn: sendBtn
   property alias theText: theText
   header: TabBar { ... }
   StackLayout {
      id: stack
      Pane {
         Flow {
            TextField {
               id: theText
            }

            Button {
               id: sendBtn
            }
         }
      }
   }
}