目录
常用元素
在qml中,元素可以被分为以下几大类。
- 可视元素(例如矩形框Rectangle)有着几何形状并且可以在屏幕上显示。
- 非可视元素(例如计时器Timer)提供了常用的功能,通常用于操作可视化元素。
可视元素
Rectangle 绘制矩形区域
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
visible: true
width: 850
height: 500
title: qsTr("test")
Item
{
Rectangle {
//id
id: rect1
//位置
x: 15; y: 12
//宽高
width: 80; height: 80
//颜色
color: "red"
}
Rectangle
{
//id
id: rect2
x: 105; y: 12
width: 80; height: 80
//渐变
gradient: Gradient
{
//渐变色
GradientStop { position: 0.0; color: "green" }
GradientStop { position: 1.0; color: "red" }
}
border.color: "red"
}
Rectangle
{
id: rect3
x: 200; y: 12
width: 80; height: 80
border.color: "red"
//设置线的宽度
border.width: 4
//设置圆角矩形的弧度
radius: 360
}
}
}
Text 显示文本
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
visible: true
width: 850
height: 500
title: qsTr("test")
Item
{
Text
{
//内容
text: 'hello world!'
//宽高
width: 300; height: 120
//颜色
color: "#303030"
//字号大小
font.pixelSize: 28
//宽度不够,设置省略号在中间
elide: Text.ElideMiddle
style: Text.Sunken
styleColor: '#FF4444'
//设置对齐方式
verticalAlignment: Text.AlignTop
//换行
wrapMode: Text.WordWrap
}
}
}
Image 显示图像。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
visible: true
width: 850
height: 500
title: qsTr("test")
Item{
Image
{
//id
id:image1
//位置
x: 12; y: 12
//宽高
width: 48
height: 118
//地址
source: "./pinwheel.png"
//当前帧
currentFrame: 1
//帧数
frameCount:1
//异步,指定本地文件系统上的映像应在单独的线程中异步加载。默认值为 false,导致用户界面线程在加载图像时阻塞。在维护响应式用户界面比使图像立即可见更可取的情况下,将异步设置为 true 非常有用。请注意,此属性仅对从本地文件系统读取的图像有效
asynchronous:false
//自动变换,此属性保存图像是否应自动应用图像转换元数据, 默认为false
autoTransform:false
//指定是否应缓存图像。默认值为 true,当有大型图片是,最好设置为false,以确保它们不会以牺牲小型“UI 元素”图像为代价进行缓存。
cache:false
//填充模式
fillMode:Image.Stretch
// Image.Stretch 图像拉伸(默认) 缩放图像以适合
// Image.PreserveAspectFit 保留方面拟合 图像均匀缩放以适合而不裁剪
// Image.PreserveAspectCrop 保存方面裁剪 图像均匀缩放以填充,必要时裁剪
// Image.Tile 图像平铺 图像水平和垂直复制
// Image.TileVertically 图像垂直平铺 图像水平拉伸并垂直平铺
// Image.TileHorizontally 图像平铺平铺 图像垂直拉伸和水平平铺
// Image.Pad 图像未转换
}
Image
{
//根据上一张图片设置位置
x: image1.x + image1.width + 20; y: image1.y
//设置相对宽高
width: image1.width/2
height: image1.height/2
source: "./pinwheel.png"
//使PreserveAspectCrop可以避免裁剪图像数据被渲染到图像边界外
fillMode: Image.PreserveAspectCrop
clip: true
}
}
}
TextInput 接受用户输入的文本框。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
visible: true
width: 850
height: 500
title: qsTr("test")
Item{
TextInput
{
text: "hello world"
id:mytext
height: 100
width: 100
color: "red"
font.pixelSize: 30
//maximumLength: 5 //最大输入长度,单位是字符,默认32767
font.bold: true //加粗,默认false
font.italic: false //是否用斜体,默认false
font.letterSpacing: 0 //字母之间距离,正表示增加,负表示缩小,0表示默认距离
font.wordSpacing: 0 //单词之间的距离,说明同上行
font.strikeout: false //设置字体是否有删除线,默认false
font.underline: false //设置字体是否有下划线,默认false
activeFocusOnPress: true //默认true,鼠标点击是否能输入。
autoScroll: true //文本长度大于宽度时是否滚动,默认true
//readOnly: true //设置只读
//inputMask: "you" //替代输入,相当text显示you,个人理解
//cursorDelegate: comp_text//光标也就是输入区域的高显,该委托起点是输入的终点
//cursorVisible: false
//cursorPosition: 200
//echoMode: TextInput.Password //显示密码符而不是输入的字符
//echoMode: TextInput.Normal //默认的显示输入的字符
//echoMode: TextInput.NoEcho //什么都不显示
//echoMode: TextInput.PasswordEchoOnEdit
//passwordCharacter: "*k" //设置模式为密码时显示的字符,第一个字母有效
//设置文本的大小写
//font.capitalization: Font.MixedCase //不使用大小写改变
//font.capitalization: Font.AllUppercase //所有的都大写
//font.capitalization: Font.AllLowercase //所有的都小写
//font.capitalization: Font.SmallCaps //使用小大写,
//font.capitalization: Font.Capitalize //单词的第一个字母大写
//font.weight: Font.Light
//font.weight: Font.Normal
//font.weight: Font.DemiBold
//font.weight: Font.Bold
//font.weight: Font.Black
//文本的对齐方式,顾名思义
//horizontalAlignment: TextInput.AlignHCenter
//horizontalAlignment: TextInput.AlignLeft
//horizontalAlignment: TextInput.AlignRight
selectByMouse: true //是否可以选择文本
//选择文本的方式,只有selectByMouse为真才有效
//mouseSelectionMode: TextInput.SelectCharacters //一个字符为单位选择,默认
//mouseSelectionMode: TextInput.SelectWords //一个单词为单位选择
selectedTextColor: "black" //设置选择文本的字体颜色
selectionColor: "white" //设置选择框的颜色
//text:"hello" //输入文本默认显示的,可以修改和增加
onAccepted: console.log("accepted") //当按下回车键触发该信号
//需要注意的是当设置了验证器validator或者掩码inputMask时,只有在输入被接受的情况下才能触发
//validator: IntValidator{bottom: 5;top:120}
//只接受5-120之内的值,当输入为4按回车时没有触发onAccepted。
//validator: DoubleValidator
//{
// bottom: 10.00
// top:150.01
// decimals: 3 //保留小数点位数
// //notation: DoubleValidator.StandardNotation
// //notation: DoubleValidator.ScientificNotation
//}
}
}
}
Button 响应用户点击的按钮。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: win
width: 800
height: 600
visible: true
title: qsTr("Hello World")
Button {
id: btn
width: 200
height: 100
//锚点
anchors.centerIn: parent
text: qsTr("This is a Button")
//自定义文本样式
contentItem: Text
{
text: btn.text
font: btn.font
//不透明度
opacity: enabled ? 1.0 : 0.3
//颜色
color: btn.down ? "#17a81a" : "#21be2b"
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
}
//自定义按钮背景
background: Image
{
opacity: enabled ? 1 : 0.3 //背景不透明度
source: "qrc:/img.jpg"
}
onCanceled: {
//当按钮在被按下时失去鼠标抓取,或者当它发出released信号
//但鼠标光标不在按钮内时,就会发出这个信号。
}
onClicked:{
//用户通过触摸、鼠标或键盘交互单击按钮
}
onDoubleClicked:{
//用户通过触摸或鼠标交互双击按钮
}
onPressAndHold:{
//用户通过触摸或鼠标交互按下按钮。
//当启用autoRepeat时,它不会被触发
}
onPressed:{
//用户通过触摸、鼠标或键盘交互按下按钮
}
onReleased:{
//用户通过触摸、鼠标或键盘交互释放按钮
}
}
}
CheckBox 处理用户选择的复选框。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: win
width: 800
height: 600
visible: true
title: qsTr("Hello World")
Row {
x:20
y:20
CheckBox {
id:ch1
checked: true
text: qsTr("First")
}
CheckBox {
id:ch2
text: qsTr("Second")
}
CheckBox {
id:ch3
checked: true
text: qsTr("Third")
}
Button{
text: "获取CheckBox状态"
onClicked: {
console.log(ch1.checked)
console.log(ch2.checked)
console.log(ch3.checked)
}
}
}
}
RadioButton 处理用户选择的单选按钮。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: win
width: 800
height: 600
visible: true
title: qsTr("Hello World")
Text
{
id: className
text: qsTr("--")
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
anchors.verticalCenterOffset: parent.height/4
font.pixelSize: 25
font.family: "微软雅黑"
}
Column
{
anchors.top: parent.top
anchors.topMargin: 10
anchors.left: parent.left
anchors.leftMargin: 10
spacing: 10
Text
{
text: qsTr("选择你喜欢的课程:")
font.pixelSize: 20
font.family: "微软雅黑"
}
Grid
{
anchors.left: parent.left
anchors.leftMargin: 30
rowSpacing: 10
columnSpacing: 40
columns: 3
//重复
Repeater
{
id: radioButtonList
model:["语文","数学","英语","物理","化学","政治","历史","美术","音乐"]
//单选按钮
RadioButton
{
text: modelData
autoExclusive:false
}
}
}
Button
{
text: "选择确定"
onClicked:
{
let str="";
for (var i = 0; i < radioButtonList.count; i++)
{
if(radioButtonList.itemAt(i).checked)
{
if(str.length!==0){str +=","}
str += radioButtonList.itemAt(i).text
}
}
className.text = str.length===0?"--":str
}
}
}
}
非可视元素
Item 所有可视元素的基类,但它本身不显示任何内容。
Item作为基本元素,没有视觉外观,属性较多,且较多控件继承它,因此,弄懂Item属性、接口、用法是学习qml关键。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: win
width: 800
height: 600
visible: true
title: qsTr("Hello World")
Item {
//项目是否具有活动焦点
activeFocus:true
//否要位于选项卡焦点链中
activeFocusOnTab:false
//锚属性,锚点提供了一种通过指定项目与其他项目的关系来定位项目的方法,只能将项目锚定到兄弟姐妹或父项
anchors:anchors.fill
// anchors.top
// anchors.bottom
// anchors.left
// anchors.right
// anchors.horizontalCenter
// anchors.verticalCenter
// anchors.baseline
// anchors.fill
// anchors.centerIn
// anchors.margins
// anchors.topMargin
// anchors.bottomMargin
// anchors.leftMargin
// anchors.rightMargin
// //锚定后的水平偏移量
// anchors.horizontalCenterOffset
// //锚定后的垂直偏移量
// anchors.verticalCenterOffset
// //指定项目基线在本地坐标中的位置
// anchors.baselineOffset
// //设置居中的锚布局时与整数个像素对齐
// anchors.alignWhenCentered
// //抗锯齿
// antialiasing
// //指定项目基线在本地坐标中的位置
// baselineOffset
// //此项的可视子项列表
// children
// //保存项目子项的集体位置和大小。返回的几何图形是项目本地的。
// childrenRect(只读属性)
// childrenRect.x
// childrenRect.y
// childrenRect.width
// childrenRect.height
//元素的子项超出父项范围后会自动裁剪
clip:false
//是否可见
visible:true
visibleChildren:true
//此属性保存项目的不透明度
opacity:1.0
//主要用于基于图像的项目,以决定项目是否应使用平滑采样
smooth:true
//属性允许在项目中自由混合可视子项和资源。如果将可视项分配给数据列表,它将成为子项,如果分配任何其他对象类型,则将其添加为资源。
data:
//否接收鼠标和键盘事件
enabled
//否在封闭的 FocusScope 内具有焦点
focus:
//隐式高度,隐式大小对于根据内容确定首选大小的组件很有用
implicitHeight
//隐式宽度
implicitWidth
layer.effect
//保持项目是否分层。默认情况下禁用分层。
layer.enabled:
//该属性定义了纹理的内部格式
layer.format:
//如果此属性为 true,则为纹理生成 mipmap
layer.mipmap:
//保存效果的源纹理属性的名称。此值必须与 layer.effect 的源纹理属性的名称匹配。
layer.samplerName:
//保持图层是否平滑变换
layer.smooth:
//该属性定义了应该渲染到纹理中的项目的矩形区域
layer.sourceRect:
//此属性定义了生成的纹理应该如何被镜像
layer.textureMirroring:
//此属性保存图层纹理的最大像素大小
layer.textureSize:
//此属性定义与纹理关联的环绕模式
layer.wrapMode:
parent:
//要按名称引用的非可视资源
resources:
//此属性保存项目绕其 transformOrigin 顺时针旋转的度数
转换 rotation:0
//此属性保存此项目的比例因子
scale:1
//包含要应用的转换列表
transform:
//保存缩放和旋转变换所围绕的原点
transformOrigin:
//此项目的转换列表
transitions:
//此属性保存项目当前状态的名称
state:
//此属性包含此项目的可能状态列表
states:
x: //相对父类绝对位置
y: //相对父类绝对位置
z:
width: //宽
height: //高
}
}
Connections 用于连接信号和槽。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: win
width: 800
height: 600
visible: true
title: qsTr("Hello World")
property alias rec1Color: rec1.color
property alias rec2Color: rec2.color
Row{
spacing: 10
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
Rectangle{
id: rec1
width: 120; height: 60
color: "red"
//自定义信号
signal sclicked();
MouseArea{
id: mouseArea1
anchors.fill: parent;
}
Component.onCompleted: {
//connect 信号连接信号
mouseArea1.clicked.connect(sclicked);
}
}
Rectangle{
id: rec2
width: 120; height: 60
color: "#00B000"
//自定义信号
signal sclicked();
MouseArea{
id: mouseArea2
anchors.fill: parent;
}
Component.onCompleted: {
//connect 信号连接信号
mouseArea2.clicked.connect(sclicked);
}
}
Connections{
target: rec1
onSclicked: {
rec2.color = "green";
rec1.color = "blue";
}
}
Connections{
target: rec2
onSclicked: {
rec1.color = "green";
rec2.color = "blue";
}
}
}
}
Timer 定时器,用于定期执行代码。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: win
width: 800
height: 600
visible: true
title: qsTr("Hello World")
Row{
spacing: 10
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
Timer {
id: myTimer
// 定时器触发的时间间隔,单位为毫秒
interval: 1000
// 是否重复触发定时器
repeat: true
// 是否启动定时器
running: true
onTriggered: {
// 定时器触发时执行的操作
console.log("定时器触发了!");
}
}
}
}
QtObject 不可视对象,用于存储属性和方法。
QtObject通常会被用来封装一些重要的属性和方法,并且可以被包含在JS脚本中进行使用。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id: win
width: 800
height: 600
visible: true
title: qsTr("Hello World")
QtObject {
id: myObject
property int myProperty: 42
function myMethod() {
console.log("Hello from myMethod!");
console.log("myProperty is " + myProperty);
}
}
}