Qt Quick 準確的移動平臺螢幕適配
阿新 • • 發佈:2019-02-02
網上大多數都是那一套公式,不適合拉伸佈局,假如有一張圖片或者一個被固定了大小的控制元件或圖片,那麼可能會失真,下面是自己實現的自適應,非常好用的說。而且網上大多數Qt quick開發群心高氣傲,根本不要人加入。很多東西可以自己研究的,樂於分享的人太少
一句話,沒圖說個JB,開幹!
下面寫一個Col容器,寬度是固定的,這種情況下,在各種移動平臺下會差別很大,不過根據我的演算法就解決了,320*480是我寫程式碼設計介面時用的介面size,在安卓上,size會根據系統的解析度而不同,因此在程式碼中把320*480作為模板,換了系統會計算比例
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
//import QtQuick.Extras 1.4
import "./UI.js" as Mui
ApplicationWindow {
id:root;
width: 320;
height: 480;
visible: true;
//獲取最終dpi
// targetDensitydpi = uiWidth / deviceWidth * devicePixelRatio * 160;
//Screen.devicePixelRatio
Component.onCompleted: {
}
property real pixelDensity: 4.46
property real multiplierH: root.height/480 //default multiplier, but can be changed by user
property real multiplierW: root.width/320 //default multiplier, but can be changed by user
function dpH(numbers) {
return Math.round(numbers*((pixelDensity*25.4)/160)*multiplierH);
}
function dpW(numbers) {
return Math.round(numbers*((pixelDensity*25.4)/160)*multiplierW);
}
Label{
anchors.centerIn: parent
id:label;
text: "..";
}
//固定寬高自適應螢幕
Column{
spacing: dpH(1);
width: dpW(440);
Repeater{
model: 17;
delegate:Rectangle{
width: parent.width;
height:dpH(40);
color: "#2a9f8d"
Text {
color: "white";
font.bold: true;
font.pointSize:14;
text:index+ ",標題dp3+"+parent.height+","+multiplierH+","+multiplierW+",";
anchors.centerIn: parent;
}
}
}
}
}
注意,設計中我把介面右邊留了空白 最後一行為第16列並且顯示不完全.這樣容易看出差異:
在電腦上的效果,此時程式的視窗大小是320*480
在電腦上手動調整介面大小的效果,此時程式的視窗大小未知
在安卓模擬器上的效果,解析度是1280*720 192dpi
來一段顯示圖片的程式碼,好用不失真
Column{
spacing: dpH(1);
width: parent.width;
Repeater{
model: 5;
delegate: BorderImage {
id: name
source: "astop.png"
width: dpW(72); height: width
border.left: dpW(1); border.top: dpH(1)
border.right: dpW(1); border.bottom: dpH(1)
}
}
}