差別
下面的筆記中将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"
}
}