简体   繁体   中英

QLineEdit: displaying overlong text as a tooltip if hovering with mouse

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?

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();
}

Here the improved function as mentioned in the comments above.

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("");
}

You can try to change the tooltip each time the text is changed:

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

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

In the cpp file, then, connect the QLineEdit textChanged() signal to the slot you defined, and implement the behavior when the text changes:

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

Finally, this is how the slot would look like:

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

I'm supposing a class called MainWindow contains the QLineEdit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM