如何使用QPlainTextEdit处理按键事件

use*_*587 5 events qt key

我已经用QT开发了大约一个星期了,我很高兴地说我正在快速地接受它.我是一名中级C++程序员,但挑选QT的某些部分证明是具有挑战性的.当用户按下Enter时,我需要处理来自QPlainTextEdit的按键事件,我认为该解决方案将涉及对小部件进行子类化.你们这些聪明人能给我一个潜在的可实施解决方案吗?

Arn*_*nce 5

要真正理解Qt和事件处理,您应该阅读文档的两个关键区域.第一个是关于事件系统的概述,第二个是非常重要的一点,它是QCoreApplication :: notify在该页面上的一个巧妙隐藏的链接.他们应该把它移到Event System文档的主页面上,因为它确实让事情变得非常清楚(至少对我来说).


Ole*_*lek 5

如果您只需要处理发送到控件的某些消息(例如按键),则无需对其进行子类化。您也可以使用事件过滤机制。这是一个简单的例子:

  1. 在基于 QObject 的类之​​一(例如窗口窗体类)中提供虚拟 eventFilter 方法。

    bool MyWindow::eventFilter(QObject *watched, QEvent *event)
    {
        if(watched == ui->myTargetControl)
        {
            if(event->type() == QKeyEvent::KeyPress)
            {
                QKeyEvent * ke = static_cast<QKeyEvent*>(event);
                if(ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter)
                {
                    // [...]
                    return true; // do not process this event further
                }
            }
            return false; // process this event further
        }
        else
        {
            // pass the event on to the parent class
            return QMainWindow::eventFilter(watched, event);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将您的类安装为目标控件的事件过滤器。表单构造函数通常是这段代码的好地方。在以下代码段中,this指的是您在其中实现该eventFilter方法的类的实例。

    ui->myTargetControl->installEventFilter(this);
    
    Run Code Online (Sandbox Code Playgroud)


sme*_*lin 4

我会尝试子类化QPlainTextEdit和重新实现QWidget::keyPressEvent

void YourTextEdit::keyPressEvent ( QKeyEvent * event )
{
  if( event->key() == Qt::Key_Return )
  {
    // optional: if the QPlainTextEdit should do its normal action 
    // even when the return button is pressed, uncomment the following line
    // QPlainTextEdit::keyPressEvent( event )

    /* do your stuff here */
    event->accept();
  }
  else
    QPlainTextEdit::keyPressEvent( event )
}
Run Code Online (Sandbox Code Playgroud)