我用QT开发了大约一个星期了,我很高兴地说我正在快速地接受它。我是一名中级C ++程序员,但挑选QT的某些部分证明是具有挑战性的。当用户按下Enter键时,我需要处理来自QPlainTextEdit的按键事件,我认为该解决方案将涉及对窗口小部件进行子类化。你们中的任何一个聪明人都能给我一个潜在的可实施解决方案吗?
答案 0 :(得分:5)
要真正了解Qt和事件处理,您应该阅读的文档有两个关键区域。第一个是The Event System的概述,第二个是非常重要的一点,它是QCoreApplication::notify页面上一个巧妙隐藏的链接。他们应该把它移到事件系统文档的主页面,因为它确实让事情变得非常清楚(至少对我来说)。
答案 1 :(得分: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 )
}
答案 2 :(得分:3)
如果你只需要处理发送给控件的一些消息 - 比如按键 - 就不需要对它进行子类化。您也可以使用事件过滤机制。这是一个简单的例子:
在一个基于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);
}
}
将您的类安装为目标控件的事件过滤器。表单构造函数通常是此代码的好地方。在以下代码段中,this
引用了您在其中实施eventFilter
方法的类的实例。
ui->myTargetControl->installEventFilter(this);
答案 3 :(得分:1)
请尝试:
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter){
//do something
}
在 keyPressEvent()功能中。