Qt 通过鼠标单击选择完整的默认文本

Qt 通过鼠标单击选择完整的默认文本,qt,Qt,我的菜单栏中有一个QLineEdit小部件,默认情况下显示文本“按ID搜索”。我如何为QLineEdit实现一个MouseClicked事件处理程序,以便当我单击LineEdit小部件时,默认文本被清除,用户可以输入他想要搜索的文本 到目前为止 #ifndef SEARCH_H #define SEARCH_H #include<QLineEdit> class search : public QLineEdit { signals:

我的菜单栏中有一个QLineEdit小部件,默认情况下显示文本“按ID搜索”。我如何为QLineEdit实现一个MouseClicked事件处理程序,以便当我单击LineEdit小部件时,默认文本被清除,用户可以输入他想要搜索的文本

到目前为止

#ifndef SEARCH_H
#define SEARCH_H
#include<QLineEdit>

class search : public QLineEdit
{
        signals:
                void clicked();

        protected:
                void mousePressEvent(QMouseEvent *);
};
#endif
\ifndef搜索
#定义搜索
#包括
类搜索:公共QLineEdit
{
信号:
无效点击();
受保护的:
void mousePressEvent(QMouseEvent*);
};
#恩迪夫

您只需将QLineEdit::MousePresseEvent(QMouseEvent*e)信号与函数连接即可。当发出此信号时,清除函数中的QLineEdit。很简单,不是吗

编辑

或者如果你有

void mousePressEvent(QMouseEvent *);
在您的小部件中,您所需要的只是为该方法编写定义。当用户在QLineEdit上按鼠标时,将调用此函数。比如:

void search::mousePressEvent(QMouseEvent *e)
{
    myQLineEdit->setText("");
}
编辑2

然后试着这样做:

class YourWidget : public QLineEdit
{
    Q_OBJECT

    protected:

    void focusInEvent(QFocusEvent* e);
};

您将要使用该属性。它显示一个灰色文本,当用户开始编辑它时(即当它获得焦点时)该文本消失


你的问题不是很清楚。请编辑它。他想知道用户在QLineEdit上按鼠标后如何清除它,而不是如何设置文本。@看起来他更想实现占位符文本。QLineEdit中已经提供了该功能,为什么要重新实现它呢?我想要一个占位符文本,但它说它是在Qt4.7中添加的。我没有找到这样的命令,但它不起作用,并且还出现了一个错误,即e参数unused@blood只是一个小错误:不完整类型的无效使用–struct QFocusEventif(e->reason()==Qt::MouseFocusReason)好的,删除它就行了。这在你的情况下是不必要的。顺便说一下,我已经检查了我第一次编辑的代码,它工作了,所以我不知道你做了什么
void YourWidget::focusInEvent(QFocusEvent* e)
{    
    if (e->reason() == Qt::MouseFocusReason)    
    {
      myQLineEdit->setText("");
    }

    // You might also call the parent method.
    QLineEdit::focusInEvent(e);
}
QLineEdit * edit = new QLineEdit;
edit->setPlaceholderText("Search by ID");