QT - How to apply a QToolTip on a QLineEdit

2019-04-03 01:03发布

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.

标签: c++ qt tooltip
2条回答
老娘就宠你
2楼-- · 2019-04-03 01:20

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?

查看更多
够拽才男人
3楼-- · 2019-04-03 01:27

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.

查看更多
登录 后发表回答