rbaleksandar
rbaleksandar

Reputation: 9701

QML: Any way of using the standard integer RGB values?

I'm using Qt 5.7 on Windows 10 and I'm relatively new to QML. I am currently adding some colors to my application and it struck me that there seems to be no way of using the plain integer RGB values (not hexadecimals) for colors. There are (as far as I know) three direct ways (without using the Qt C++ functions of QColor in combination with the QML code) of setting an item to a specific color:

All three coloring conventions above represent the same color (RGB: 128, 128, 128). I really prefer using the normal integer values since I'm more familiar with those. Is it possible to use those without any extra effort in QML?

Upvotes: 2

Views: 8975

Answers (2)

Stephen Quan
Stephen Quan

Reputation: 26139

Instead of converting ints to floats, we can convert from ints to hexadecimal:

    function rgb(r, g, b, a) {
        return "#"
             + (a ? a.toString(16).padStart(2, "0") : "")
             + r.toString(16).padStart(2, "0")
             + g.toString(16).padStart(2, "0")
             + b.toString(16).padStart(2, "0");
    }

Here's a demonstration with Red, Green, Blue sliders:

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Page {
    property var col: rgb(redSlider.value, greenSlider.value, blueSlider.value)

    ColumnLayout {
        Frame {
            Rectangle {
                implicitWidth: 200
                implicitHeight: 200
                color: col
                Frame {
                    anchors.centerIn: parent
                    background: Rectangle { }
                    Text {
                        text: col
                    }
                }
            }
        }

        SliderText {
            id: redSlider
            value: 176
        }

        SliderText {
            id: greenSlider
            value: 196
        }

        SliderText {
            id: blueSlider
            value: 222
        }
    }

    function rgb(r, g, b, a) {
        return "#"
             + (a ? a.toString(16).padStart(2, "0") : "")
             + r.toString(16).padStart(2, "0")
             + g.toString(16).padStart(2, "0")
             + b.toString(16).padStart(2, "0");
    }
}

//SliderText.qml
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
RowLayout {
    property alias value: slider.value
    Slider {
        id: slider
        from: 0
        to: 255
        stepSize: 1
    }
    Text {
        text: slider.value
    }
    Text {
        text: slider.value.toString(16).padStart(2, "0")
    }
}

You can Try it Online!

Upvotes: 1

Mitch
Mitch

Reputation: 24416

No.

Building off what @Gwen said, you can define your own function that takes integers and does the conversion to floats, and then call that everywhere.

Upvotes: 4

Related Questions