Qt 学习之路 2(79):QML 组件
?
下面我們通過一個例子來演示這種方法。我們要創建一個帶有文本說明的Rectangle,這個矩形將成為一個按鈕。用戶可以點擊矩形來響應事件。
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import QtQuick 2.0 Rectangle { ????id: root ????property alias text: label.text ????signal clicked ????width: 116; height: 26 ????color: "lightsteelblue" ????border.color: "slategrey" ????Text { ????????id: label ????????anchors.centerIn: parent ????????text: "Start" ????} ????MouseArea { ????????anchors.fill: parent ????????onClicked: { ????????????root.clicked() ????????} ????} } |
?
我們將這個文件命名為 Button.qml,放在 main.qml 同一目錄下。這里的 main.qml 就是 IDE 幫我們生成的 QML 文件。此時,我們已經創建了一個 QML 組件。這個組件其實就是一個預定義好的Rectangle。這是一個按鈕,有一個Text用于顯示按鈕的文本;有一個MouseArea用于接收鼠標事件。用戶可以定義按鈕的文本,這是用過設置Text的text屬性實現的。為了不對外暴露Text元素,我們給了它的text屬性一個別名。signal clicked給這個Button一個信號。由于這個信號是無參數的,我們也可以寫成signal clicked(),二者是等價的。注意,這個信號會在MouseArea的clicked信號被發出,具體就是在MouseArea的onClicked屬性中調用個這個信號。
下面我們需要修改 main.qml 來使用這個組件:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import QtQuick 2.0 Rectangle { ????width: 360 ????height: 360 ????Button { ????????id: button ????????x: 12; y: 12 ????????text: "Start" ????????onClicked: { ????????????status.text = "Button clicked!" ????????} ????} ????Text { ????????id: status ????????x: 12; y: 76 ????????width: 116; height: 26 ????????text: "waiting ..." ????????horizontalAlignment: Text.AlignHCenter ????} } |
?
在 main.qml 中,我們直接使用了Button這個組件,就像 QML 其它元素一樣。由于 Button.qml 與 main.qml 位于同一目錄下,所以不需要額外的操作。但是,如果我們將 Button.qml 放在不同目錄,比如構成如下的目錄結果:
| 1 2 3 4 5 | app |- QML |?? |- main.qml |- components ???? |- Button.qml |
那么,我們就需要在 main.qml 的import部分增加一行import ../components才能夠找到Button組件。
有時候,選擇一個組件的根元素很重要。比如我們的Button組件。我們使用Rectangle作為其根元素。Rectangle元素可以設置背景色等。但是,有時候我們并不允許用戶設置背景色。所以,我們可以選擇使用Item元素作為根。事實上,Item元素作為根元素會更常見一些。
轉載于:https://www.cnblogs.com/lvdongjie/p/4810706.html
總結
以上是生活随笔為你收集整理的Qt 学习之路 2(79):QML 组件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#_观察者模式
- 下一篇: 推荐一本书给大家《不懂带人 你就自己做到