在对话框中,我有一个QLineEdit和一个按钮。我想在按下按钮时启用QLineEdit的工具提示(在其中或在下面)。请给我一个代码片段。
这是一个简单的示例:
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;
};
Run Code Online (Sandbox Code Playgroud)
如您所见,没有简单的方法来启用某些小部件的工具提示。您必须提供的全局坐标QToolTip::showText。
执行此操作的另一种方法是创建QHelpEvent自己,然后使用发布此事件QCoreApplication::postEvent。这样,您可以使用来指定要在小部件中显示的文本QWidget::setToolTip。不过,您仍然必须提供全局坐标。
我非常想知道为什么要这样做,因为仅当您将鼠标悬停或询问“这是什么”信息时,才会显示工具提示。要将其用于其他用途,似乎设计不好。如果您想向用户发送消息,为什么不使用QMessageBox?
如果您需要 QLineEdit 的工具提示,那么问题是什么?只需设置:
myLineEdit->setToolTip("Here is my tool tip");
Run Code Online (Sandbox Code Playgroud)
但是,如果您只需要button在按下某些文本后显示一些文本,那么这里有另一种解决方案:例如on_myBytton_clicked(),创建一个插槽并将其连接到您的按钮。在 slot 中使用setText()函数执行您的文本QLabel,QTextEdit以及位于表单上的其他小部件。
希望有帮助。