2 ways:
1) try deriving from QLabel and overwrite the event function:
Source code | |
1 2 3 4 5 6 7 8 9 10 11 12 | bool event( QEvent * e ) { bool retVal = QLabel::event(e); if (e->type() == QEvent:: MouseButtonPress) { foo(); retVal = true; } return retVal; } |
Example:
class MainWindow : public QMainWindow
{
public:
MainWindow();
protected:
bool eventFilter(QObject *obj, QEvent *ev);
private:
QTextEdit *textEdit;
};
MainWindow::MainWindow()
{
textEdit = new QTextEdit;
setCentralWidget(textEdit);
textEdit->installEventFilter(this);
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == textEdit) {
if (event->type() == QEvent::KeyPress) { //随便判断什么事件都可以了
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
qDebug() << "Ate key press" << keyEvent->key();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}
2万+

被折叠的 条评论
为什么被折叠?



