Skip to content

Instantly share code, notes, and snippets.

@M-Mueller
Created July 5, 2017 12:39
Show Gist options
  • Save M-Mueller/d4b50efb83bda80ddc2f1fd7d1b79231 to your computer and use it in GitHub Desktop.
Save M-Mueller/d4b50efb83bda80ddc2f1fd7d1b79231 to your computer and use it in GitHub Desktop.
QLineEdit with icon (or button)
// depending on the stylesheet:
const int defaultPadding = 10;
const int border = 3;
const int iconSize = lineedit->fontMetrics().xHeight()*4; // or whatever size looks good
auto lineedit = QLineEdit();
lineedit->setStyleSheet(QString(R"CSS(
QLineEdit {
padding-left: %1px;
}
)CSS").arg(defaultPadding*2 + iconSize)); // make space for the icon in the padding
auto label = new QLabel(lineedit);
label->setPixmap(icon.pixmap(iconSize));
label->setFixedSize(iconSize, iconSize);
label->setStyleSheet(R"CSS(
QLabel {
padding: 0px;
border: none;
}
)CSS");
// reposition the label when the lineedit changes size
lineedit->installEventFilter(new FunctionalEventFilter([=](QObject* obj, QEvent* event) // or create a QObject subclass that does that
{
if (auto resizeEvent = dynamic_cast<QResizeEvent*>(event))
label->move(defaultPadding + border, resizeEvent->size().height()/2 - label->height()/2); // position is relative to top-left of lineedit
}, label));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment