[英]Is it possible to make a 'broken' border with text for QLineEdit in PyQt/PySide2
是否可以将 PyQt5/PySide2 中的输入字段设置为如下所示:输入字段
关于样式 QLineEdit 的官方文档( https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit )没有提供很多示例。 到目前为止,我尝试弄乱边框属性,但我无法得到任何与我想要的东西密切相关的东西。 我的另一个想法是将上面的图片用作背景图片,并从 qlineedit 中删除边框和背景,使其看起来像是图片的一部分。 这种方法的问题是它不再是可拉伸的。
是否有可能让我的 qlineedit 看起来像图片中的那样,还是我应该放弃这个想法?
您可以通过继承 QLineEdit 并定义自定义的paintEvent 来实现这一点。 QFontMetrics 将获取要添加为 QLineEdit 上的 label 的文本的宽度和高度。 然后它可用于定义所需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)
您可以创建新的 object,而不是创建 QLineEdit,例如NewLineEdit('Input Field')
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.