3

I have an editable QWebView. In eventFilter, I want to change the Qt::Left_Key event to Qt::Right_Key and vise versa for textCursor position in webview. Here's my code:

bool MyClass::eventFilter(QObject *o, QEvent *e)
{
    if(o == p->webView) {
        switch(static_cast<int>(e->type()))
        {
        ...
        case QEvent::KeyPress:
            if(static_cast<QKeyEvent*>(e)->key() == Qt::Key_Left) {
                QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier);
                QApplication::postEvent(p->webView, event);
                return true;
            }
            else
            if(static_cast<QKeyEvent*>(e)->key() == Qt::Key_Right) {
                QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier);
                QApplication::postEvent(p->webView, event);
                return true;
            }
        break;
        }
    }

    return QWidget::eventFilter(o,e);
}

But when I create a QKeyEvent and post it to application, I guess the eventFilter call again for QKeyEvent that I posted to application and webview textCursor that moved to left (for example), again move to right and seems it's position don't change.

How can I solve this problem? Can anyone help?

4

1 回答 1

2

I check my intuition about spontaneous property available in QEvent.

Here an example that shows how it is used to inversed key navigation (Left, Right) in a QTextEdit. It should be trivial to transpose to your web view.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //install the filter for your "source" of key event
    ui->sourceEdit->installEventFilter(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::eventFilter(QObject *src, QEvent *ev)
{
    if (src == ui->sourceEdit) {
        if (ev->type() == QEvent::KeyPress) {
            if (ev->spontaneous()) {
                qDebug() << "I am spontaneous";

                QKeyEvent* keyEv = static_cast<QKeyEvent*>(ev);

                if (keyEv->key() == Qt::Key_Left) {
                    QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier);
                    QApplication::postEvent(ui->sourceEdit, event);
                    return true;
                } else if (keyEv->key() == Qt::Key_Right) {
                    QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier);
                    QApplication::postEvent(ui->sourceEdit, event);
                    return true;
                }
            } else {
                //here pass all event that are not coming from the underlying System.
                qDebug() << "not spontaneous";
            }
        }
    }
    return QMainWindow::eventFilter(src, ev);
}
于 2013-09-14T13:28:22.227 回答