是否可以在 PyQt/PySide2 中为 QLineEdit 创建带有文本的 'broken' 边框

Is it possible to make a 'broken' border with text for QLineEdit in PyQt/PySide2

是否可以将 PyQt5/PySide2 中的输入字段样式设置为如下所示: input field

关于 QLineEdit 样式的官方文档 (https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit) 没有提供很多示例。 到目前为止,我尝试弄乱边界属性,但我无法得到任何与我想要的东西密切相关的东西。 我的另一个想法是使用上面的图片作为背景图片,并从 qlineedit 中删除边框和背景,使其看起来像是图片的一部分。这种方法的问题是它不能再拉伸了。

是否有可能使我的 qlineedit 看起来像图片中的那样,还是我应该放弃这个想法?

您可以通过子类化 QLineEdit 并定义自定义 paintEvent 来实现此目的。 QFontMetrics 将获取要添加为 QLineEdit 上的标签的文本的宽度和高度。然后它可用于定义所需的 margin-top 和裁剪边框 space。边界线可以用painter path画出来,这样才能有真正透明的破碎区域。

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class NewLineEdit(QLineEdit):

    def __init__(self, label, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.label = label
        self.lrect = self.fontMetrics().boundingRect(label)
        self.setStyleSheet(f'''
        QLineEdit {{
            background-color: rgba(0, 0, 0, 0%);
            border: none;
            padding: 9px;
            margin-top: {self.lrect.height() / 2}px;
            color: blue;
        }}''')
        self.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.setMinimumWidth(self.lrect.width() + 52)

    def paintEvent(self, event):
        super().paintEvent(event)
        w, h = self.width(), self.height()
        lh = self.lrect.height() / 2
    
        path = QPainterPath()
        path.moveTo(30, lh + 3)
        path.lineTo(9, lh + 3)
        path.quadTo(3, lh + 3, 3, lh + 9)
        path.lineTo(3, h - 9)
        path.quadTo(3, h - 3, 9, h - 3)
        path.lineTo(w - 9, h - 3)
        path.quadTo(w - 3, h - 3, w - 3, h - 9)
        path.lineTo(w - 3, lh + 9)
        path.quadTo(w - 3, lh + 3, w - 9, lh + 3)
        path.lineTo(42 + self.lrect.width(), lh + 3)

        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing)
        qp.setPen(QPen(QColor('#aaa'), 3))
        qp.drawPath(path)
        qp.setPen(Qt.black)
        qp.drawText(36, self.lrect.height(), self.label)

不是创建 QLineEdit,而是创建新对象,例如 NewLineEdit('Input Field')

结果: