【问题标题】:QlineEdit selectAll doesn't work?QlineEdit selectAll 不起作用?
【发布时间】:2016-02-26 13:44:26
【问题描述】:

我使用以下代码。其中lineEdit->selectAll() 工作由pushButton 调用, 在首次启动时由eventFilter 调用。尽管label->setText 一直正常工作。为什么?

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->lineEdit->installEventFilter(this);
}

void Widget::on_pushButton_clicked()
{
    ui->lineEdit->selectAll();
}

bool Widget::eventFilter(QObject *object, QEvent *event)
{
    if (object == ui->lineEdit && event->type() == QEvent::FocusIn )
    {
        ui->lineEdit->selectAll();
        ui->label->setText("Focused!");
        return false;
    }
    if (object == ui->lineEdit && event->type() == QEvent::FocusOut )
    {
        ui->label->setText("unFucused!");
        return false;
    }
    return false;
}

UPD:按照 Ilya 的建议做了。还是有同样的问题。

void myLine::focusInEvent(QFocusEvent* event)
{
    setText("Focused!");
    selectAll();
}

void myLine::focusOutEvent(QFocusEvent* event)
{
    setText("UnFocused!");
}

【问题讨论】:

  • 为什么不用QWidget的focusInEvent / focusOutEvent?
  • 如果我由设计师创建QLineEdit,是否可以(使用focusInEvent)?
  • 我不明白为什么不呢?
  • 我应该添加这个:void lineedit::focusInEvent(QFocusEvent* event) { ui->lineEdit->selectAll(); QLineEdit::focusInEvent(event); } ?但是代码在哪里?
  • 是的,它有效吗?

标签: qt qlineedit selectall


【解决方案1】:

在这里找到答案Select text of QLineEdit on focus

改为ui->lineEdit->selectAll() 应该使用QTimer::singleShot(0,ui->lineEdit,SLOT(selectAll())), 因为mousePressEvent 紧跟在focusInEvent 之后,所以focusInEvent 中选择的文本会被mousePressEvent 取消选择。

【讨论】:

  • 谢谢,这也让我明白了。我可以对事件触发的顺序做出任何假设吗?
【解决方案2】:

没有真正回答这个问题,但有一种更“标准”的方式来定制这些事件。

  • 创建一个 QLineEdit 子类并定义您自己的 focusInEvent / focusOutEvent 处理程序。

  • 如果您使用的是 UI 设计器,请将您的 lineEdit 提升为您的子类(右键单击 >“提升为”)。

【讨论】:

    【解决方案3】:

    因为你用错了eventFilter:

    bool Widget::eventFilter(QObject *object, QEvent *event)
    {
        if (object == ui->lineEdit && event->type() == QEvent::FocusIn )
        {
            ui->lineEdit->selectAll();
            ui->label->setText("Focused!");
        }
        if (object == ui->lineEdit && event->type() == QEvent::FocusOut )
        {
            ui->label->setText("unFucused!");
        }
        return QWidget::eventFilter(object, event);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多