您可以通过继承 QLineEdit 并定义一个自定义的paintEvent 来实现这一点。 QFontMetrics 将获取要作为标签添加到 QLineEdit 上的文本的宽度和高度。然后它可以用来定义一个想要的margin-top 和剪裁的边框空间。可以使用画家路径绘制边界线,以获得真正透明的破碎区域。
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')
结果: