Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Qcolor value to hex value?

Tags:

I have implemented a QColor dialog box which opens on certain condition. To get the selected color after final selection I use the method selectedColor() which returns the value in QColor. When I print that value, it's like this:

<PyQt4.QtGui.QColor object at 0x01DD7880> 

I want color value in hex value like this: #DFDFDF (for grey). If it's not hex, correct me.

Is there any function to convert that?

Any suggestions welcome.

like image 924
vettipayyan Avatar asked Jan 06 '11 17:01

vettipayyan


People also ask

How is hex code calculated?

First ValueTake the first number, 220, and divide by 16. 220 / 16 = 13.75, which means that the first digit of the 6-digit hex color code is 13, or D. Take the remainder of the first digit, 0.75, and multiply by 16. 0.75 (16) = 12, which means that the second digit of the 6-digit hex color code is 12, or C.

How do you set QColor?

To create a QColor based on either HSV or CMYK values, use the toHsv() and toCmyk() functions respectively. These functions return a copy of the color using the desired format. In addition the static fromRgb(), fromHsv() and fromCmyk() functions create colors from the specified values.


2 Answers

You need to print selectedColor().name() to print the actual color value in hex. See the QColor Documentation

like image 59
Jason B Avatar answered Sep 22 '22 08:09

Jason B


To amplify a bit, maybe confuse, maybe clarify... (For Python newbies)

color = QColorDialog.getColor(pWidget.textBackgroundColor(), pWidget, 'Get Text Highlighting Color') 

The above will return a QColor using the QColorDialog, for those of us who don't want to be stuck with named colors like 'Blue', 'red', green etc.

fg = color.name() 

In this case I am converting the QColor to a string HEX for use in a style sheet.

Widget.setStyleSheet('background-color: ' + bg + ';color: ' + fg) 

This is how such a converted value can be used in a style sheet.

Note how to concatenate more than one stylesheet attribute. Also, side note, sometimes changing one attribute cancels previous changes to others.

like image 39
Mike Sr Avatar answered Sep 22 '22 08:09

Mike Sr