qml之简单图片浏览器
前面或多或少我们学习了一些qml相关的简单的知识,今天我们就用前面学过的来做一个简单的图片浏览器。代码很简单,里面都有注释,希望对大家有所帮助。
源代码:
import QtQuick 2.10
import QtQuick.Window 2.10
import QtQuick.Controls.Styles 1.4
import QtQuick.Dialogs 1.2
import QtQuick.Controls 2.2
Window {
visible: true
width: 640 //宽度
height: 480 //高度
minimumWidth: 480 //最小宽度
minimumHeight: 320 //最小高度
title: qsTr("QtImageViewer")//窗口标题
//加载动画
BusyIndicator{
id:busy;
running: false;//显示加载动画
anchors.centerIn: parent;//显示在窗体中央
z:2;
}
Text {
id: stateText
visible: false //不可见
anchors.centerIn: parent;
z:3;
}
Image {
id: img;
asynchronous: true; //开启异步加载
cache: false; //不缓存图片
anchors.left: parent.left; //父窗体左边对齐
anchors.leftMargin: 20;
anchors.right: parent.right; //父窗体右边对齐
anchors.rightMargin: 20;
anchors.top: parent.top; //父窗体顶部对齐
anchors.topMargin: 20;
anchors.bottom: openBtn.top;//父窗体底部对齐
anchors.bottomMargin: 10;
fillMode: Image.PreserveAspectFit; //缩放适应
onStatusChanged: {
//加载完成处理
if(img.status == Image.Ready)
{
busy.running = false;
stateText.visible = false;
}
//加载失败处理
else if(img.status == Image.Error)
{
busy.running = false;
stateText.visible = true;
stateText.text = qsTr("加载失败");
}
//加载中处理
else if(img.status == Image.Loading)
{
busy.running = true;
stateText.visible = false;
}
}
}
Button{
id:openBtn;
text: qsTr("浏览");
anchors.left: parent.left;
anchors.leftMargin: 30;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 10;
background: Rectangle{
implicitWidth: 75;//实际宽度
implicitHeight: 30;//实际高度
color: openBtn.hovered ?"#6A6AFF" : "#DDDDFF" ; //鼠标划过颜色
border.width: openBtn.pressed ? 2 : 1; //边框宽度
//边框颜色
border.color: (openBtn.pressed || openBtn.hovered) ?
"green" : "#888888";
}
onClicked: {
fds.open();
}
z:4;
}
Text {
id: imgPath
anchors.left: openBtn.right;
anchors.leftMargin: 10;
anchors.verticalCenter: openBtn.verticalCenter;
font.pointSize: 12;//字体大小
}
FileDialog{
id:fds;
nameFilters: ["图像文件 (*.png *.jpg)"];
onAccepted: {
img.source = fds.fileUrl;//设置图片路径
var path = new String(fds.fileUrl);
imgPath.text = path.slice(8); //截取字符串,从第八位开始
}
}
}
还没有评论,来说两句吧...