[英]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.