通过QPainter在PyQT中构造QIcon

0 投票
1 回答
1841 浏览
提问于 2025-04-17 06:04

我知道这是可能的,但我就是搞不定正确的代码。我想要的很简单:一个单色的矩形,大小大约是20x20,应该是通过QPainter来绘制的。然后我想把这个绘制好的矩形用作QComboBox中的一个图标。有没有什么建议?提前谢谢你们。

1 个回答

3

看起来你只需要用到 QPixmap.fill 这个方法就可以解决你的问题:

from PyQt4 import QtGui

class Window(QtGui.QComboBox):
    def __init__(self):
        QtGui.QComboBox.__init__(self)
        self.resize(200, 25)
        pixmap = QtGui.QPixmap(20, 20)
        for color in 'red orange yellow green blue grey violet'.split():
            pixmap.fill(QtGui.QColor(color))
            self.addItem(QtGui.QIcon(pixmap), color.title())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

撰写回答