QLineEdit: displaying overlong text as a tooltip if hovering with mouse
c++, qlineedit, qt, tooltip
Solution
I would create a custom class derived from QLineEdit like so:
#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 whatever:
#include <QtGui>
#include "LineEdit.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
LineEdit edit;
edit.show();
return app.exec();
}
Problem
Under Windows, I've seen a nice feature: If I hover with the mouse over a short text field which contains overlong text not fitting completely into the field, a tooltip opens, displaying the complete contents of the text field. Can someone point me to a code snippet which does this with QLineEdit?