I've been developing with QT for around a week now and am pleased to say that I'm picking it up really fast. I'm an intermediate C++ programmer but picking up some parts of QT is proving to be challenging. I need to process key press events from the QPlainTextEdit when the user presses enter and I presume that the solution will involve sub classing the widget. Can any of you smart guys give me a potential implementable solution?
问题:
回答1:
To really understand Qt and event handling there are two key areas of the documentation you should read. The first is the overview on The Event System and the second is a very important bit which is a cleverly hidden link on that page for QCoreApplication::notify. They should really move that to the main page of the Event System documentation as it really makes things quite clear (to me at least).
回答2:
i would try subclassing QPlainTextEdit
and reimplementing 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 )
}
回答3:
If you only need to handle some messages sent to the control - like the key-presses - there is no need to subclass it. You can alternatively use the event filtering mechanism. Here is a simple example:
Provide virtual eventFilter method in one of your QObject-based classes (e.g. the window form class).
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); } }
Install your class as the event filter for the target control. Form constructor is usually a good place for this code. In the following snippet
this
refers to the instance of class in which you implemented theeventFilter
method.ui->myTargetControl->installEventFilter(this);
回答4:
please try :
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter){
//do something
}
in your keyPressEvent() function.