QML知识笔记(六)
Qt Quick Controls模块提供一个控件的集合供用户开发图形化界面使用。基本控件有命令按钮,文本框,标签,单选按钮,组合框和复选框等,通常用于显示程序界面,接受用户的输入和选择,是最常用的控件。
以下程序包含了常用控件和布局
import QtQuick
import QtQuick.Controls 2.5 //导入Qt组件库
import QtQuick.Layouts 1.3 //导入布局库
ApplicationWindow{ //主应用窗口
width: 500
height: 320
visible: true
title: qsTr("学生信息表")
Item{ //QML通用的根元素
width: 640
height: 480
anchors.fill: parent
//行布局,左边的
RowLayout{
x: 50
y: 35
spacing: 10
ColumnLayout{ //列布局
spacing: 8
RowLayout{ //姓名
spacing: 0
Label{
text: "姓名"
}
TextField{
id: name
implicitWidth: 150
//placeholderText设定当文本框为空时其中要显示的文本
placeholderText: qsTr("请输入...")
focus: true
}
}
RowLayout{ //年龄
spacing: 0
Label{
text: "年龄"
}
TextField{
id: age
implicitWidth: 150
//验证器,只有输入符合验证要求时才能被文本框接受
validator: IntValidator{
bottom: 16
top: 26
}
}
}
GroupBox{
id: group1
title: "性别"
Layout.fillWidth: true
RowLayout{
//男
RadioButton{
id: radio1
text: qsTr("男")
checked: true //默认选中
anchors.horizontalCenter: parent.horizontalCenter
Layout.minimumWidth: 85 //设置最小宽度
}
//女
RadioButton{
id: radio2
text: qsTr("女")
Layout.minimumWidth: 85 //设置最小宽度
}
}
}
RowLayout{
spacing: 0
//专业
Label{
text: "专 业"
}
ComboBox{
id: combobox
Layout.fillWidth: true
currentIndex: 0 //初始选择索引为0
model: ["计算机","通信工程","信息网络"]
width: 200
}
}
GroupBox{
id: group2
title: qsTr("爱好")
Layout.fillWidth: true
//网格布局
GridLayout{
id: hobby
columns: 3
CheckBox{
text: qsTr("游泳")
checked: true
}
CheckBox{
text: qsTr("跑步")
}
CheckBox{
text: qsTr("打篮球")
}
CheckBox{
text: qsTr("踢足球")
checked: true
}
CheckBox{
text: qsTr("画画")
}
CheckBox{
text: qsTr("打游戏")
}
CheckBox{
text: qsTr("网购")
checked: true
}
CheckBox{
text: qsTr("其他")
}
}
}
//提交按钮
Button{
id: submit
anchors.right: group2.right
text: "提交"
implicitWidth: 50
onClicked: {
var hobbytext = "";//存放学生爱好文本
for(var i = 0;i < 7;i++){
hobbytext += hobby.children[i].checked?(hobby.children[i].text + "、"):"";
}
if(hobby.children[7].checked){
hobbytext += "...";
}
var setText = radio1.checked?"男":"女";
subInfo.text = "我的名字叫" + name.text + ",是个" + age.text + "岁" + setText +
"生,\r\n所学专业是" + combobox.currentText + ",业余喜欢\r\n" + hobbytext;
}
}
}
//列布局,右边的
ColumnLayout{
Layout.alignment: Qt.AlignTop
Label{
text: "基本信息"
font.pixelSize: 15
font.bold: true
}
TextArea{
id: subInfo
Layout.fillHeight: true
implicitWidth: 240
text: "学生个人资料"
font.pixelSize: 14
}
}
}
}
}