Reputation: 416
Is it possible to style the input field in PyQt5/PySide2 to look like this: input field
Official docs on styling QLineEdit (https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit) do not provide many examples. So far I tried messing with border properties but I cannot get anything even closely related to what I want. Another idea I have is to use the picture above as a background image and remove border and background from the qlineedit to make it seem like it's a part of the picture. The problem with this approach is that it will not be stretchable anymore.
Is it even possible to make my qlineedit look like the one in the picture or should I just abandon this idea?
Upvotes: 0
Views: 662
Reputation: 6112
You could achieve this by subclassing QLineEdit and defining a custom paintEvent. QFontMetrics will get the width and height of the text to be added as a label on the QLineEdit. Then it can be used to define a desired margin-top
and clipped border space. The border line can be drawn with a painter path in order to have a truly transparent broken region.
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)
Instead of creating a QLineEdit you would create the new object such as NewLineEdit('Input Field')
Outcome:
Upvotes: 1