區別
下面的筆記中將QtQuick.Controls 2簡稱爲qml2,QtQuick.Controls簡稱爲qml1。
最直觀的的區別就是qml2的控件及界面風格更加美觀,qml2提供了一套谷歌風格的控件,與安卓上的控件風格一樣,基本不需要再自定義了,控件本身的外觀和點擊效果已經可以滿足大部分環境。
詳細說明見官方文檔:QtQuick.Controls 2與QtQuick.Controls的區別
qml2中調用qml1中的控件
1、類型重命名
錯誤:直接在代碼中同時調用QtQuick.Controls 2模塊和QtQuick.Controls模塊會出錯,Cannot assign to non-existent property “style”。
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Controls 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
//qml1
Button {
x: 100
y: 200
text: "A button"
style: ButtonStyle {
background: Rectangle {
implicitWidth: 100
implicitHeight: 25
border.width: control.activeFocus ? 2 : 1
border.color: "#888"
radius: 4
gradient: Gradient {
GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
}
}
}
}
//qml2
Button{
x: 300
y: 200
text: "B button"
}
}
正確:正確的做法是將使用到的QtQuick.Controls模塊進行類型重命名,然後再調用其中的控件。
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4 as Controls14
import QtQuick.Controls.Styles 1.4 as Styles14
import QtQuick.Controls 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
//qml1
Controls14.Button {
x: 100
y: 200
text: "A button"
style: Styles14.ButtonStyle {
background: Rectangle {
implicitWidth: 100
implicitHeight: 25
border.width: control.activeFocus ? 2 : 1
border.color: "#888"
radius: 4
gradient: Gradient {
GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
}
}
}
}
//qml2
Button{
x: 300
y: 200
text: "B button"
}
}
2、將控件封裝成組件
MyButton.qml
import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
Button {
x: 100
y: 200
text: "A button"
style: ButtonStyle {
background: Rectangle {
implicitWidth: 100
implicitHeight: 25
border.width: control.activeFocus ? 2 : 1
border.color: "#888"
radius: 4
gradient: Gradient {
GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
}
}
}
}
直接調用即可
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
//qml1
MyButton{
onClicked:
{
console.log("aaaa")
}
}
//qml2
Button{
x: 300
y: 200
text: "B button"
}
}