QT - How to apply a QToolTip on a QLineEdit

自闭症网瘾萝莉.ら 提交于 2019-12-21 06:04:14

问题


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.


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/3014879/qt-how-to-apply-a-qtooltip-on-a-qlineedit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!