Qt里面要对界面进行颜色赋值,可以采用十六进制(#FFFFFF)或者Qt.rgba(0.5,0.5,0.5,1)这2种方法,这2个方法使用起来都不是很方便, 无法使用rgb值进行设置,也是比较麻烦,因此想到qml支持js函数的方法,进行将rgb转换成十六进制的格式,然后进行使用
使用的时候可以单独创建一个js文件,将这个转换函数写入到其中.
然后使用
import "CommonFunction.js" as CommonFunctionHandler进行导入js文件
函数调用方式:CommonFunctionHandler.rgb(255,182,193)
下面使用效果
源码
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import QtQuick.Controls.Styles 1.4
import QtQuick.Layouts 1.3
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
function rgb(r, g, b){
var ret = (r << 16 | g << 8 | b)
return ("#"+ret.toString(16)).toUpperCase();
}
RowLayout{
anchors.fill: parent
spacing: 30
Label{
Layout.fillWidth: true
}
Repeater{
model:[rgb(120,120,230),
rgb(60,120,230),
rgb(120,0,230),
rgb(120,120,0),
rgb(90,120,60)]
Button{
background: Rectangle{
color:modelData
implicitHeight:40
implicitWidth:40
}
onClicked: {
console.log(modelData)
}
}
}
Label{
Layout.fillWidth: true
}
}
}