pyforms - 基于变量值的动态样式

pyforms - dynamic styling based on variable value

我正在开发一个 pyform 控件,它只接受 url 作为输入。

为了实现这一点,我从 ControlText 派生了我的 class 并添加了一个按键事件处理程序,它根据正则表达式测试当前值。

现在我想根据 style.css 中所示的变量以某种方式更改控件的外观。


Controls.py

import pyforms
from   pyforms.Controls import ControlText
import re

class ControlUrl(ControlText):

    def __init__(self, label="", default=None, helptext=None, regex="^((https?:)?\/\/)?(\w+(:\w+)?@)?(((([a-zA-Z\d]{1,2}|[a-zA-Z\d][\w\-]{0,62}[a-zA-Z\d])\.){1,}[\w\-]{2,6})|(\d{1,3}(\.\d{1,3}){3})|([\d:]{2,39}))(:\d{2,6})?(\/[\w.~!+,*:@%-]+)*\/?(\?([\w.~!+%,*:@-]+(=[\w.~!+%,*:@-]+)?)(&[\w.~!+%,*:@-]+(=[\w.~!+%,*:@-]+)?)*)?(#[\w.~!+%,*:@-])?$"):
        self._regex = regex
        super(ControlUrl, self).__init__(label, default, helptext)

    def init_form(self):
        self._pattern = re.compile(self._regex)
        self.key_pressed_event = self.__key_pressed
        super(ControlUrl, self).init_form()

    def __key_pressed(self, event):
        is_url = self._pattern.search(self.value) != None
        self.valid = is_url

style.css

#_urlinput[valid="true"] {
    background-color: red;
}

我更喜欢用 css 解决它,但每个解决方案都值得赞赏。

动态样式基于 QPropertys,可以使用 setProperty 设置,css 选择器看起来像 [propertyname=propertyvalue]


代码:

import sys
import pyforms
from   pyforms.Controls import ControlText
import re


class ControlUrl(ControlText):

    def __init__(self, *args, regex="^((https?:)?\/\/)?(\w+(:\w+)?@)?(((([a-zA-Z\d]{1,2}|[a-zA-Z\d][\w\-]{0,62}[a-zA-Z\d])\.){1,}[\w\-]{2,6})|(\d{1,3}(\.\d{1,3}){3})|([\d:]{2,39}))(:\d{2,6})?(\/[\w.~!+,*:@%-]+)*\/?(\?([\w.~!+%,*:@-]+(=[\w.~!+%,*:@-]+)?)(&[\w.~!+%,*:@-]+(=[\w.~!+%,*:@-]+)?)*)?(#[\w.~!+%,*:@-])?$", **kwargs):
        self._regex = regex
        super(ControlUrl, self).__init__(*args, **kwargs)

    def init_form(self):
        self._pattern = re.compile(self._regex)
        self.key_pressed_event = self.__key_pressed
        super(ControlUrl, self).init_form()

    def __key_pressed(self, event):
        self._valid = self._pattern.search(self.value) != None
        base = self.form.lineEdit
        base.setProperty("valid", self._valid)

        #without these lines the style is not applied
        base.style().unpolish(base)
        base.style().polish(base)

Css:

QLineEdit[valid=false] {
    border: 1px solid #991903;
    border-radius: 4px;
}
QLineEdit[valid=false]:focus {
    border-color: #db391c;
}

更多信息: