colorreg = QRegExp("^#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$") colorvalidator = QRegExpValidator() colorvalidator.setRegExp(colorreg)
self.line_R.setValidator(QIntValidator(0,255)) self.line_G.setValidator(QIntValidator(0, 255)) self.line_B.setValidator(QIntValidator(0, 255))
def validate_hex_color(hex_color): # 去除前导和尾随的空格 hex_color = hex_color.strip() # 检查长度 if len(hex_color) != 7: return False, "颜色代码长度应为7个字符" # 检查格式 if hex_color[0] != "#" or not hex_color[1].isdigit() or not hex_color[2].isdigit() or \ not hex_color[3].isdigit() or not hex_color[4].isdigit() or \ not hex_color[5].isdigit() or not hex_color[6].isdigit(): return False, "颜色代码格式不正确" # 转换RGB值并验证 r = int(hex_color[1:3], 16) g = int(hex_color[3:5], 16) b = int(hex_color[5:7], 16) if r < 0 or r > 255 or g < 0 or g > 255 or b < 0 or b > 255: return False, "RGB值必须在0-255范围内" return True, "颜色代码有效"