QLineEdit: display overlay text as a tooltip on mouseover

On Windows, I saw a nice feature: if I hover over a short text field that contains overlapping text that doesn't fit completely into the field, a tooltip opens that displays the full contents of the text field.

Can someone point me to a piece of code that does this with QLineEdit?

+4
source share
3 answers

I would create a custom class derived from QLineEdit as follows:

#ifndef LINEEDIT_H #define LINEEDIT_H #include <QtGui> class LineEdit : public QLineEdit { Q_OBJECT public: LineEdit(); public slots: void changeTooltip(QString); }; LineEdit::LineEdit() { connect(this, SIGNAL(textChanged(QString)), this, SLOT(changeTooltip(QString))); } void LineEdit::changeTooltip(QString tip) { QFont font = this->font(); QFontMetrics metrics(font); int width = this->width(); if(metrics.width(tip) > width) { this->setToolTip(tip); } else { this->setToolTip(""); } } #include "moc_LineEdit.cpp" #endif // LINEEDIT_H 

Then just add it to something:

 #include <QtGui> #include "LineEdit.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); LineEdit edit; edit.show(); return app.exec(); } 
+4
source

The feature mentioned in the comments above has been improved here.

 void LineEdit::changeTooltip(QString tip) { QFont font = this->font(); QFontMetrics metrics(font); // get the (sum of the) left and right borders; // note that Qt doesn't have methods // to access those margin values directly int lineMinWidth = minimumSizeHint().width(); int charMaxWidth = metrics.maxWidth(); int border = lineMinWidth - charMaxWidth; int lineWidth = this->width(); int textWidth = metrics.width(tip); if (textWidth > lineWidth - border) this->setToolTip(tip); else this->setToolTip(""); } 
+2
source

You can try to change the hint every time you change the text:

First, define a private slot to edit the textChanged () signal from QLineEdit: (in the header file from the class where your QTextEdit belongs)

 .... private slots: void onTextChanged(); .... 

In the cpp file, connect the QLineEdit textChanged () signal to the specified slot and implement the behavior when changing the text:

 // In constructor, or wherever you want to start tracking changes in the QLineEdit connect(myLineEdit, SIGNAL(textChanged()), this, SLOT(onTextChanged())); 

Finally, the slot will look like this:

 void MainWindow::onTextChanged() { myLineEdit->setTooltip(myLineEdit->text()); } 

I assume that a class called MainWindow contains a QLineEdit.

0
source

All Articles