Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT - How to apply a QToolTip on a QLineEdit

Tags:

c++

tooltip

qt

On a dialog I have a QLineEdit and a button. I want to enable a tool tip for the QLineEdit(in it or under it) when I press the button. Please give me a code snippet.

like image 984
Narek Avatar asked Dec 17 '22 00:12

Narek


2 Answers

Here is a simple example:

class MyWidget : public QWidget
{
        Q_OBJECT

    public:

        MyWidget(QWidget* parent = 0) : QWidget(parent)
        {
            QVBoxLayout* layout = new QVBoxLayout(this);
            edit = new QLineEdit(this);
            layout->addWidget(edit);
            showButton = new QPushButton("Show tool tip", this);
            layout->addWidget(showButton);
            hideButton = new QPushButton("Hide tool tip", this);
            layout->addWidget(hideButton);

            connect(showButton, SIGNAL(clicked(bool)), this, SLOT(showToolTip()));
            connect(hideButton, SIGNAL(clicked(bool)), this, SLOT(hideToolTip()));
        }

    public slots:

        void showToolTip()
        {
            QToolTip::showText(edit->mapToGlobal(QPoint()), "A tool tip");
        }

        void hideToolTip()
        {
            QToolTip::hideText();
        }

    private:

        QLineEdit* edit;
        QPushButton* showButton;
        QPushButton* hideButton;
};

As you can see, there is no easy way to just enable the tool tip of some widget. You have to provide global coordinates to QToolTip::showText.

Another way to do this is to create a QHelpEvent yourself and post this event using QCoreApplication::postEvent. This way, you can specify the text to be shown in your widget using QWidget::setToolTip. You still have to provide global coordinates, though.

I am really interested in why you want to do this since tool tips are intended to be shown only when you hover your mouse or when you ask for the "What's this" information. It looks like bad design to use it for something else. If you want to give a message to the user, why don't you use QMessageBox?

like image 167
mtvec Avatar answered Dec 24 '22 02:12

mtvec


If you need tooltip for QLineEdit, so what is the problem? Just set:

myLineEdit->setToolTip("Here is my tool tip");

But if you need just to show some text after some button was pressed, here the another solution: create a slot, for example on_myBytton_clicked() and connect it to your button. In slot do the setText() function with your text on QLabel, QTextEdit and etc widgets located on your form.

Hope it help.

like image 23
mosg Avatar answered Dec 24 '22 01:12

mosg