在QML中包含了很少的Element,因為夠少,夠簡單,所以學起來很容易。在QML里面沒有像Qt GUI程序里面類似QPushButton,QCheckBox之類標准控件。QML把我們能在屏幕上看到的內容(文字和圖片)都濃縮為了Rectangle,Image和Text等等的幾個簡單元素,並通過一個稍微抽象點的MouseArea(鼠標區域)來響應我們的鼠標事件,通過Keys來響應我們的鍵盤輸入。加上QML之間可以相互引用,這使得我們能通過非常簡單的幾個Rectangle做出非常精美的程序界面。
在QML中有幾個非常好的特性,可以提高我們的寫好一個漂亮界面的效率。這幾個特性主要是下面幾個:
1. 用於排版布局的Anchor系統,可以非常容易的實現動態布局;
anchor的說明如下圖所示:
2. 狀態機,可以非常方便的讓程序在不同狀態下做出相應相應;
3. 屬性綁定,也是犀利的東西;
4. 動畫元素非常多,使用QML的動畫元素,你可以通過幾句非常簡單的代碼,做出花哨的動畫。
5. ……
雖然,QML很強大,但是現在還在成長期,在很多地方也存在不足。比如,我們現在應該還沒辦法使用MouseArea來捕獲鼠標滾輪事件,至少我現在還沒有找到比較簡單的方法來實現。Image也不能顯示內存中的二進制數據的圖片,以及我們無法關閉Image的緩存機制。並且我們不能屏蔽WebView右鍵菜單,我們不能捕獲到WebView的鏈接點擊事件。以上所說的不足應該說是因為QML給我們提供的Element太簡單造成的。雖然說可以通過C++來寫QML的Element來解決相應的問題,但是畢竟比較麻煩,而且過於局限。
畢竟,QML相關技術是Qt主推的東西,也是趨勢,所以我認為還是有必要學習她。
// main.h
#include <QApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>
// main.cpp
class Stopwatch : public QObject
{
Q_OBJECT
public:
Stopwatch();
Q_INVOKABLE bool isRunning() const;
public slots:
void start();
void stop();
private:
bool m_running;
};
復制代碼
main.cpp
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDeclarativeView view;
view.rootContext()->setContextProperty("stopwatch",
new Stopwatch);
view.setSource(QUrl::fromLocalFile("main.qml"));//qt調用qml
//view.setSource(QUrl("qrc:/main.qml"));
view.show();
return app.exec();
}
復制代碼
// main.qml
import Qt 4.7
Rectangle {
width: 300
height: 300
radius: 20
Text {
id: helloText
text: "ImageView"
x: 80
y: 5
anchors.horizontalCenter: page.horizontalCenter
font.pointSize: 24; font.bold: true
}
MouseArea {
id: mouseArea; anchors.fill: parent
onClicked: {
if (stopwatch.isRunning())//qml調用c++方法
{
stopwatch.stop() ;
helloText.color = "black";
}
else
{
stopwatch.start();//qml調用c++方法
helloText.color = "red";
}
}
}
}