def initData(self):
     # __COLORS = ['white', 'black', 'gray', 'green', 'red', 'yellow', \
     #             '#FA8072', '#87CEFA', '#1E90FF', \
     #             'rgb(255, 0, 0)', 'rgba(255, 0, 0, 75%)']
     __COLORS = QColor.colorNames()      # Predefined colors
     __BORDER_STYLES = ['none', 'dashed', 'dot-dash', 'dot-dot-dash', 'dotted', 'double', 'groove', \
                        'inset', 'outset', 'ridge', 'solid']
     __COLORS.sort()
     __BORDER_STYLES.sort()
     # fill the items
     self.widgetBackgroundColor.addItems(__COLORS)
     self.widgetColor.addItems(__COLORS)
     self.widgetBorderColor.addItems(__COLORS)
     self.widgetSelectionColor.addItems(__COLORS)
     self.widgetBorderStyle.addItems(__BORDER_STYLES)
     # set default value to widgets
     self.widgetBackgroundColor.setCurrentText('white')
     self.widgetColor.setCurrentText('black')
     self.widgetBorderColor.setCurrentText('black')
     self.widgetSelectionColor.setCurrentText('yellow')
     self.widgetBorderStyle.setCurrentText('none')
     self.widgetBorderWidth.setValue(1)
     self.widgetBorderRadius.setValue(1)
     # set default value to variables
     self.inputBackgroundColor = self.widgetBackgroundColor.currentText()
     self.inputColor = self.widgetColor.currentText()
     self.inputBorderColor = self.widgetBorderColor.currentText()
     self.inputSelectionColor = self.widgetSelectionColor.currentText()
     self.inputBorderStyle = self.widgetBorderStyle.currentText()
     self.inputBorderWidth = self.widgetBorderWidth.value()
     self.inputBorderRadius = self.widgetBorderRadius.value()
Exemple #2
0
    def draw_smth(self):
        self.qp.setBrush(QColor(0, 0, 255))
        z, x, y = randint(5, 200), randint(5, 680), randint(5, 580)

        color = QColor(choice(QColor.colorNames()))

        self.qp.setBrush(QColor(color))
        self.qp.drawEllipse(x, y, z, z)
    def _readColor(self, widgetValues, f, isBorder=False):
        global colorNames

        mode = widgetValues["comboData"]
        if mode == OptionalColorWidgetFunc.NONE:
            return None

        if mode == ColorWidgetFunc.EXPRESSION:
            val = self.evaluateExpression(widgetValues["editText"], f)
            try:
                if isinstance(val, str):
                    a = val.split(",")
                    if len(a) >= 3:
                        a = [max(0, min(int(c), 255)) for c in a[:3]]
                        return "0x{:02x}{:02x}{:02x}".format(a[0], a[1], a[2])
                    return val.replace("#", "0x")

                raise
            except:
                logMessage("Wrong color value: {}".format(val))
                return "0"

        if mode == ColorWidgetFunc.RANDOM or f is None:
            if len(colorNames) == 0:
                colorNames = QColor.colorNames()
            colorName = random.choice(colorNames)
            colorNames.remove(colorName)
            return QColor(colorName).name().replace("#", "0x")

        # feature color
        symbol = self.layer.renderer().symbolForFeature(f, self.renderContext)
        if symbol is None:
            logMessage('Symbol for feature cannot be found: {0}'.format(
                self.layer.name()))
            symbol = self.layer.renderer().symbols()[0]
        else:
            sl = symbol.symbolLayer(0)
            if sl:
                if isBorder:
                    return sl.strokeColor().name().replace("#", "0x")

                if symbol.hasDataDefinedProperties():
                    expr = sl.dataDefinedProperty("color")
                    if expr:
                        # data defined color
                        rgb = expr.evaluate(f, f.fields())

                        # "rrr,ggg,bbb" (dec) to "0xRRGGBB" (hex)
                        r, g, b = [
                            max(0, min(int(c), 255))
                            for c in rgb.split(",")[:3]
                        ]
                        return "0x{:02x}{:02x}{:02x}".format(r, g, b)

        return symbol.color().name().replace("#", "0x")
 def paintEvent(self, e):
     painter = QPainter()
     painter.begin(self)
     if self.parent.mode == 'Paint':
         self.draw_points(painter, self.points, Qt.black, 3)
         self.draw_figures(painter)
     else:
         self.draw_figures(painter)
         self.draw_points(painter, self.locations,
                          QColor(choice(QColor.colorNames())), 10)
     painter.end()
Exemple #5
0
    def initUI(self):
        self.__size = QSize(400, 400)
        self.__board = QPixmap(self.__size)  # 新建QPixmap作为画板,宽350px,高250px
        self.__board.fill(Qt.white)  # 用白色填充画板

        self.__IsEmpty = True  # 默认为空画板
        self.EraserMode = False  # 默认为禁用橡皮擦模式

        self.__lastPos = QPoint(0, 0)
        self.__currentPos = QPoint(0, 0)

        self.__painter = QPainter()

        self.__thickness = 2  # 默认画笔粗细为2px
        self.__penColor = QColor("black")  # 设置默认画笔颜色为黑色
        self.__colorList = QColor.colorNames()  # 获取颜色列表
Exemple #6
0
    def __InitData(self):

        #新建QPixmap作爲畫板,尺寸爲__size
        self.__board = QPixmap(self.__size)
        self.__board.fill(Qt.black)  #用白色填充畫板

        self.__IsEmpty = True  #默認爲空畫板
        self.EraserMode = False  #默認爲禁用橡皮擦模式

        self.__lastPos = QPoint(0, 0)  #上一次鼠標位置
        self.__currentPos = QPoint(0, 0)  #當前的鼠標位置

        self.__painter = QPainter()  #新建繪圖工具

        self.__thickness = 20  #默認畫筆粗細爲10px
        self.__penColor = QColor("white")  #設置默認畫筆顏色爲白色
        self.__brushColor = QColor("white")  #設置默認筆刷顏色爲白色
        self.__colorList = QColor.colorNames()  #獲取顏色列表
Exemple #7
0
    def change_fixationpoint_color(self, color):
        # for x in QColor.colorNames():
        #     print(x)
        if any(x == color.Color for x in QColor.colorNames()):
            meta = self.qml_fixationpoint.metaObject()
            res = meta.invokeMethod(self.qml_fixationpoint,
                                    "change_fixationpoint_color",
                                    Qt.BlockingQueuedConnection,
                                    Q_RETURN_ARG(QVariant),
                                    Q_ARG(QVariant, color.Color))

            return ChangeFixationpointColorResponse('Success.')
        else:
            return ChangeFixationpointColorResponse(
                'Specified color "{}" is not contained in'
                ' "QColor.colorNames()".'.format(color.Color) +
                'See "http://doc.qt.io/qt-5/qcolor.html" for available colors.'
            )
Exemple #8
0
def text_to_qcolor(text):
    """
    Create a QColor from specified string
    Avoid warning from Qt when an invalid QColor is instantiated
    """
    color = QColor()
    if not is_string(text):  # testing for QString (PyQt API#1)
        text = str(text)
    if not is_text_string(text):
        return color
    if text.startswith('#') and len(text) == 7:
        correct = '#0123456789abcdef'
        for char in text:
            if char.lower() not in correct:
                return color
    elif text not in list(QColor.colorNames()):
        return color
    color.setNamedColor(text)
    return color
Exemple #9
0
def text_to_qcolor(text):
    """
    Create a QColor from specified string
    Avoid warning from Qt when an invalid QColor is instantiated
    """
    color = QColor()
    if not is_string(text): # testing for QString (PyQt API#1)
        text = str(text)
    if not is_text_string(text):
        return color
    if text.startswith('#') and len(text)==7:
        correct = '#0123456789abcdef'
        for char in text:
            if char.lower() not in correct:
                return color
    elif text not in list(QColor.colorNames()):
        return color
    color.setNamedColor(text)
    return color
Exemple #10
0
def main():
    rgb = tribColours.rgbDict()
    print(rgb)

    teststring = """
    QPushButton!:hover {
                background : tribSnow;
                 }
                
    QPushButton:hover {
                border: 2px solid tribStone;
                backgroundL tribStone
                       }
    """

    print(teststring)
    print(coloursub(teststring))
    print(tablecolourflagstyle())
    print(QColor.colorNames())
Exemple #11
0
    def _readColor(self, widgetValues, f, isBorder=False):
        mode = widgetValues["comboData"]
        if mode == OptionalColorWidgetFunc.NONE:
            return None

        if mode == ColorWidgetFunc.EXPRESSION:
            val = self.evaluateExpression(widgetValues["editText"], f)
            try:
                if isinstance(val, str):
                    a = val.split(",")
                    if len(a) >= 3:
                        a = [max(0, min(int(c), 255)) for c in a[:3]]
                        return "0x{:02x}{:02x}{:02x}".format(a[0], a[1], a[2])
                    return val.replace("#", "0x")

                raise
            except:
                logMessage("Wrong color value: {}".format(val))
                return "0"

        if mode == ColorWidgetFunc.RANDOM or f is None:
            self.colorNames = self.colorNames or QColor.colorNames()
            color = random.choice(self.colorNames)
            self.colorNames.remove(color)
            return QColor(color).name().replace("#", "0x")

        # feature color
        symbols = self.renderer.symbolsForFeature(f, self.renderContext)
        if not symbols:
            logMessage(
                "Symbol for feature not found. Please use a simple renderer for {0}."
                .format(self.name))
            return "0"

        symbol = symbols[0]
        if isBorder:
            sl = symbol.symbolLayer(0)
            if sl:
                return sl.strokeColor().name().replace("#", "0x")

        return symbol.color().name().replace("#", "0x")
Exemple #12
0
    def _readColor(self, widgetValues, f=None, isBorder=False):
        global colorNames

        mode = widgetValues["comboData"]
        if mode == OptionalColorWidgetFunc.NONE:
            return None

        if mode == ColorWidgetFunc.RGB:
            return widgetValues["editText"]

        if mode == ColorWidgetFunc.RANDOM or f is None:
            if len(colorNames) == 0:
                colorNames = QColor.colorNames()
            colorName = random.choice(colorNames)
            colorNames.remove(colorName)
            return QColor(colorName).name().replace("#", "0x")

        # feature color
        symbol = self.layer.renderer().symbolForFeature(f, self.renderContext)
        if symbol is None:
            logMessage('Symbol for feature cannot be found: {0}'.format(
                self.layer.name()))
            symbol = self.layer.renderer().symbols()[0]
        else:
            sl = symbol.symbolLayer(0)
            if sl and isBorder:
                return "0xffff00"  #sl.outlineColor().name().replace("#", "0x")    #TODO: QGIS 3

            if sl and symbol.hasDataDefinedProperties():
                expr = sl.dataDefinedProperty("color")  #TODO: QGIS 3
                if expr:
                    # data defined color
                    rgb = expr.evaluate(f, f.fields())

                    # "rrr,ggg,bbb" (dec) to "0xRRGGBB" (hex)
                    r, g, b = [
                        max(0, min(int(c), 255)) for c in rgb.split(",")[:3]
                    ]
                    return "0x{0:02x}{1:02x}{2:02x}".format(r, g, b)

        return symbol.color().name().replace("#", "0x")
Exemple #13
0
    def loadVars(self, qssStr=None):
        """扫描qsst模板文件中的所有变量定义,引用的变量;
        把引用的变量放到varUsed列表中;
        把引用但未定义变量赋值为''放在varDict中;
        把定义的变量放到varDict中
        """
        if qssStr is None:
            qssStr = self.srctext
        self.varUsed = list(
            set(re.findall(r':[ \t\w,.:()]*[$]([\w]+)', qssStr)))
        varsDefined = list(
            set(
                re.findall(r'[$](\w+)\s*=[ \t]*([#(),.\w]*)[\t ]*[\r\n;\/]+',
                           qssStr)))

        self.varDict = {}
        valerr = False
        for var, val in varsDefined:
            if not valerr:
                if val in QColor.colorNames():
                    self.varDict[var] = val
                else:
                    valerrind = re.match(
                        r'#[0-9A-Fa-f]{1,8}|rgb\(\s*[0-9]*\s*(,\s*[0-9]*\s*){2}\)|rgba\(\s*[0-9]*\s*(,\s*[0-9]*\s*){3}\)',
                        val)
                    if not valerrind:
                        valerr = True
                    else:
                        self.varDict[var] = val

        self.varUndefined = []
        for varused in self.varUsed:
            if varused not in self.varDict.keys():
                self.varDict[varused] = ''
                self.varUndefined.append(varused)
        return not valerr  # 如果有变量的值格式不正确返回false
Exemple #14
0
def get_qcolor(*args):
    """
    Return a QColor either from a RGB tuple of int, a RGB Hex Code,
    a supported Qt color name, or a QPalette color group.

    https://srinikom.github.io/pyside-docs/PySide/QtGui/QPalette.html
    https://srinikom.github.io/pyside-docs/PySide/QtGui/QColor.html
    """
    if isinstance(args[0], QColor):
        return args[0]

    if isinstance(args[0], tuple):
        return QColor(*args[0])

    if isinstance(args[0], str):
        if args[0].startswith('#') or args[0] in QColor.colorNames():
            return QColor(args[0])

        try:
            return getattr(QStyleOption().palette, args[0])().color()
        except AttributeError:
            pass

    raise ValueError("The provided color argument is not valid")
Exemple #15
0
 def populateList(self):
     for i, colorName in enumerate(QColor.colorNames()):
         color = QColor(colorName)
         self.insertItem(i, colorName)
         self.setItemData(i, color, Qt.DecorationRole)
Exemple #16
0
 def initData(self):
     # 初始化数据
     # 变量名前有两个下划线代表类的私有变量
     #    获取QT中的颜色列表(字符串的List)
     self.__colorList = QColor.colorNames()
     self.__GeoItemView = GeoItemView()
Exemple #17
0
 def initItems(self):
     size = QSize(100, 100)
     for cname in QColor.colorNames():
         self.makeItem(size, cname)
Exemple #18
0
from PyQt5.QtGui import QColor

command = {}
for color in QColor.colorNames():
    command[color] = color


def colr(blue):
    clr = ""
    try:
        if command[blue]:
            return command[blue]
    except:
        clr = "black"
        return clr


def findMath(text):
    text += " "
    items = []
    it = ""
    for item in text:
        if item == " ":
            items.append(it)
            it = ""
        else:
            it += item
    return items


def calculateMath(items):
Exemple #19
0
 def populateWithColors(self, comboBox):
     colorNames = QColor.colorNames()
     for name in colorNames:
         comboBox.addItem(name, name)
Exemple #20
0
 def populateWithColors(self, comboBox):
     colorNames = QColor.colorNames()
     for name in colorNames:
         comboBox.addItem(name, name)
 def populateList(self):
     for i, colorName in enumerate(QColor.colorNames()):
         color = QColor(colorName)
         self.insertItem(i, colorName)
         self.setItemData(i, color, Qt.DecorationRole)
Exemple #22
0
 def __init__(self, parent=None):
     super().__init__(parent)
     for i, clr in enumerate(QColor.colorNames()):
         self.addItem(clr, QColor(clr).name())
         self.model().item(i).setBackground(QColor(clr))