Created
March 22, 2014 03:22
-
-
Save krets/9700614 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" I needed some unique icons for numerous pyside scripts. This helped. | |
""" | |
from PySide import QtCore, QtGui | |
import sys | |
import operator | |
def getIcon(inputStr='', saturation=.8, value=.9, size=128): | |
""" Creates a QIcon of a single letter on a solid color based on an input | |
string. The same string will always produce the same background color. | |
This will generate an oversized QPixmap so that QIcon can derive most | |
necessary sizes. | |
""" | |
# ensure that the inputStr is a string and not empty. | |
inputStr = str(inputStr) | |
if inputStr == '': | |
inputStr = ' ' | |
color = QtGui.QColor() | |
color.setHsvF(getStringHue(inputStr), saturation, value) | |
pixmap = QtGui.QPixmap(size,size) | |
pixmap.fill(color) | |
font = QtGui.QFont() | |
font.setBold(True) | |
font.setPixelSize(.8*size) | |
painter = QtGui.QPainter(pixmap) | |
painter.setRenderHint(painter.TextAntialiasing) | |
painter.setFont(font) | |
painter.setPen(QtCore.Qt.white) | |
painter.drawText(pixmap.rect(), QtCore.Qt.AlignCenter, inputStr[0].upper()) | |
painter.end() | |
return QtGui.QIcon(pixmap) | |
def getStringHue(inputStr, steps=16): | |
""" Return a float value used for Hue. | |
""" | |
total = reduce(operator.add, map(ord, str(inputStr))) | |
return 1.0/steps * (total % steps) | |
def main(): | |
app = QtGui.QApplication([]) | |
dlg = QtGui.QDialog() | |
lyt = QtGui.QVBoxLayout() | |
dlg.setLayout(lyt) | |
text = "Testing 123" | |
if len(sys.argv) > 1: | |
text = sys.argv[1] | |
icn = getIcon(text) | |
lbl = QtGui.QLabel() | |
lbl.setPixmap(icn.pixmap(128,128)) | |
lyt.addWidget(lbl) | |
dlg.setWindowIcon(icn) | |
dlg.show() | |
return app.exec_() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment