CellRendererProgress, display fractional value like "99.5%"?

I’m using Gtk#. It seens that CellRendererProgress allows only integers. In the TreeStore I defined the value as float, but when I bound that to value, it became integer, so a value like 99.5 was displayed as 99%.

        var st = new Gtk.TreeStore(typeof(bool), typeof(string), typeof(float), typeof(string));
        var iter = st.AppendValues(true, "hello", 7.04, "gtk");
        var r3 = new Gtk.CellRendererProgress();
        MyTree.Columns[1].AddAttribute(r3, "value", 2);

I tried binding the value to text, but then it was displayed like 99.500000000.

MyTree.Columns[1].AddAttribute(r3, "text", 2);

So, what is the best way to display it like 99.5%? I could add a string value like "99.5%" to the TreeStore, but that is a duplicate datum, and does not look clean. Is there anyway to provide a custom “formatter” for “text”?

What happens if you bind the other way round, i.e. you store a string in your TreeStore for the text property, and bind the text property to the value property (unidirectional binding)

For the approach you used, you can register a custom function to convert GValues from float to string with g_value_register_transform_func, but it is application global so it’s a really bad solution. I do not recommend it.

Ok, here is the right solution: you can bind the text property to the value property with GBinding. A GBinding binds two properties and you can supply a transformation function. That should work flawlessly

Thanks, but how can I apply that “GBinding” to TreeView’s column?

That did not show the progress bar. It output an error message like this:

unable to set property ‘value’ of type ‘gint’ from value of type ‘gchararray’

Yeah, it appears that there is no built-in conversion from a string GValue to an int GValue. You can add one using g_value_register_transform_func, though.

You should apply the GBinding to the CellRendererProgress. But I don’t know if Glib# has wrappers for GBinding.

It’s difficult to fine examples and documentation for Gtk, and it’s almost impossible to find those for Gtk#. Literally, documentation does not exist (I’m using Gtk# 3). Anyways, I took an easier way which may not be efficient. I created a child class that sets the Value and Text.

    class XXX : CellRendererProgress
    {
        [Property("realvalue")]            
        public float RealValue
        {
            set
            {
                Value = (int)value;
                Text = $"{value:F1}%";
            }
        }
    }

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.