예제 #1
0
def color_from_string(string, alpha):
    xs = string.strip()
    regex = QRegExp(REGEX_QCOLOR)
    match = regex.exactMatch(xs)
    if match:
        return QColor(xs)

    regex = QRegExp(REGEX_FN_RGB)
    match = regex.exactMatch(xs)
    if match:
        captured_texts = regex.capturedTexts()
        return QColor(int(captured_texts[-3]), int(captured_texts[-2]), int(captured_texts[-1]))

    if alpha:
        regex = QRegExp(REGEX_HEX_RGBA)
        match = regex.exactMatch(xs)
        if match:
            return QColor(_HEXDEC[xs[1:3]], _HEXDEC[xs[3:5]], _HEXDEC[xs[5:7]], _HEXDEC[xs[7:9]])

        regex = QRegExp(REGEX_FN_RGBA)
        match = regex.exactMatch(xs)
        if match:
            captured_texts = regex.capturedTexts()
            return QColor(
                int(captured_texts[-4]), int(captured_texts[-3]), int(captured_texts[-2]), int(captured_texts[-1]))

    return QColor()
예제 #2
0
def string_is_hex(color_str):
    """
    Returns whether or not given string is a valid hexadecimal color
    :param color_str: str
    :return: bool
    """

    if color_str.startswith('#'):
        color_str = color_str[1:]
    hex_regex1 = QRegExp('^[0-9A-F]{3}$', Qt.CaseInsensitive)
    hex_regex2 = QRegExp('^[0-9A-F]{6}$', Qt.CaseInsensitive)
    hex_regex3 = QRegExp('^[0-9A-F]{8}$', Qt.CaseInsensitive)
    if hex_regex1.exactMatch(color_str) or hex_regex2.exactMatch(color_str) or hex_regex3.exactMatch(color_str):
        return True

    return False