0

I am trying to "decorate" a QLineEdit, or to be more accurate, to paint my own custom frame around it, to get the following result:

enter image description here

I tried to use Qt Style Sheets (CSS), but this will only enable trivial frame decorating (changing width/color/size etc...), nothing fancy like the above.

I also tried inheriting from QLineEdit and overriding its void QLineEdit::paintEvent(QPaintEvent* e), but then I realized that reimplementing it means I will lose the QLineEdits "editness" (sorry for butchering the language here) - the textbox, the cursor, and the ability to insert text.

How can I achieve the above text box?
Is this a combination of QLabel perfectly located behind a QLineEdit?

so.very.tired
  • 2,958
  • 4
  • 41
  • 69

1 Answers1

1

Try to use composition. Create your own Widget inherited it from QWidget, paint what you want in QWidget::paintEvent and place QLineEdit above it. Probably you'll have to center it and use css for QLineEdit to make it look smooth.

class MyWidget: public QWidget
{
explicit MyWidget(QWidget* parent = 0):
QWidget(parent),
line_edit(new QLineEdit(this))
{
     //  place line_edit in center of QWidget
}

private: 
QLineEdit* line_edit;
}

Or you can override void QLineEdit::paintEvent(QPaintEvent* e) like this

void QLineEdit::paintEvent(QPaintEvent* e)
{
      //paint your border
      QLineEdit::paintEvent(e);
}

And you won't lose the QLineEdits "editness".

Konstantin T.
  • 994
  • 8
  • 22
  • Thanks for the answer. Couple more Qs: for the first suggestion; How do I do that? will my QWidget hold a QLineEdit as a data member? as a child-widget? For the second suggestion; I tried it, but the textbox took all the space and completely hide my drawings... – so.very.tired Dec 28 '18 at 09:48
  • Ok, great! Thank you! I did that, and set the size of the parent MyWidget to be slightly bigger than the QLineEdit child (so I'll have enough space to paint around it), now how do I move the QLineEdit inside MyWidget so it will be vertically-centered? – so.very.tired Dec 28 '18 at 10:07
  • Use some of `QLayout`s or move it manualy by calling `QWidget::setGeometry`. – Konstantin T. Dec 28 '18 at 11:11