Simple color fill QIcons in Qt
Asked Answered
I

2

16

I need to create a menu that changes the background of a QWidget. I'd like to place a QIcon that represents the selected color into the QActions which populates the QMenu. I'd like to not have to pop out Photoshop and paint the icons manually. Is it possible to program a simple icon that is filled with a certain color? This way I can have an arbitrary number of QActions if needed, and I won't have to make whole bunch of icons in Photoshop. \

Irritation answered 12/11, 2012 at 19:58 Comment(0)
A
24

You can construct a QIcon from a QPixmap. QPixmap can be constructed with a given size, then filled with a colour using 'fill'.

For example, to create a red 100x100 icon:

QPixmap pixmap(100,100);
pixmap.fill(QColor("red"));
QIcon redIcon(pixmap);
Adaline answered 12/11, 2012 at 20:15 Comment(2)
This will fill only the transparent parts of the image, right? I mean, can this be used to fill the transparent parts of a QIcon with color?Lipolysis
I'm afraid I don't understand. This code creates an entirely new icon that is a solid red square.Adaline
M
13

Just figured out how to change color from icon to any other color. Therefore, the image of the icon must consist of one solid color (here: 'black') which can be converted using a pixmap and its masking ability into another color (like 'red'):

pixmap = QPixmap(filename)
mask = pixmap.createMaskFromColor(QColor('black'), Qt.MaskOutColor)
pixmap.fill((QColor('red')))
pixmap.setMask(mask)

btNew = QToolButton()
btNew.setIcon(QIcon(pixmap))
Mercator answered 14/7, 2016 at 8:43 Comment(4)
Cool, though createMaskFromColor(QColor('transparent'), Qt.MaskInColor) works better for meLauzon
The topic is tagged with C++, but this is no valid C++ code. Would like to edit it but the reviewers rejected it for reasons I don't know. Beside this, the solution worked for me after porting it to C++.Benoite
I think you are right - I didn't recognize that the question was related to c++ - but I also think it is not meant to change an already existing answer that much... And I don't know if your code is stable - so I cannot accept it for myself. I think, you should answer yourself! Thanks for the hint.Mercator
@Lauzon That's such a useful change that personally I think it warrants its own answer, and I'd vote for that :-) Anyway, thanks to both! Works great.Tighten

© 2022 - 2024 — McMap. All rights reserved.