QLineEdit with custom button

ArmanHunanyan picture ArmanHunanyan · Jan 20, 2014 · Viewed 10k times · Source

I need to implement LineEdit widget with possibility to add tool buttons at the right end of text area. I know two ways of doing that but both solutions seems ugly.

1) add tool buttons as child widgets of QLineEdit and handle resizeEvent to position them correctly. The main disadvantage is that if text is enough long it may appear under tool buttons.

2) Another solution is to put line edit and buttons inside frame and overwrite style to hide lineEdits frame and make QFrame look like QLineEdit.

I need a best way to implement such widget. Also my widget should be style aware.

Answer

Moritz Jasper picture Moritz Jasper · Jan 29, 2015

As of Qt 5.2 one can use QLineEdit::addAction(...) to insert custom buttons. (Qt Docs)

Example (assume we're inside the definition of MyClass):

QLineEdit *myLineEdit = new QLineEdit(this);
QAction *myAction = myLineEdit->addAction(QIcon("test.png"), QLineEdit::TrailingPosition);
connect(myAction, &QAction::triggered, this, &MyClass::onActionTriggered);

enter image description here