2

I'm trying to use a keyPressEvent, but it is only working when the window has focus and not any of the QWidgets.

Here is my code:

In customdialog.h:

class CustomDialog : public QDialog, public Ui::CustomDialog 
{
    Q_OBJECT

private:
    Ui::CustomDialog *ui;

    QString lastKey;

public:
    CustomDialog(QWidget * parent = 0);

protected:
    void keyPressEvent(QKeyEvent *e);

};

In customdialog.cpp:

void CustomDialog::keyPressEvent(QKeyEvent *e)
{
    lastKey = e->text();
    qDebug() << lastKey;
}

How can I make all widgets within this class use the same keyPressEvent?

4

2 回答 2

2

您可以通过为 CustomDialog 的每个子项安装事件过滤器来解决您的问题:

void CustomDialog::childEvent(QChildEvent *event)
{
    if (event->added()) {
        event->child()->installEventFilter(this);
    }
}

bool CustomDialog::eventFilter(QObject *, QEvent *event)
{
    if (event->type() == QEvent::KeyPress)
        keyPressEvent(static_cast<QKeyEvent*>(event));
    return false;
}

但是由于每个被忽略的 keyPress 事件都会发送到父小部件,因此您可以为同一事件多次调用 keyPressEvent。

于 2013-11-12T20:16:21.413 回答
0

我最终决定在这种情况下不使用 keyPressEvent 来实现我的目的。我只需要在 QTextBrowser 中按下最后一个键。这是我最终做的事情:

connect(ui->textBrowser, SIGNAL(textChanged()), this, SLOT(handleTextBrowser()));

void CustomDialog::handleTextBrowser()
{    
    QTextCursor cursor(ui->textBrowser->textCursor());

    QString key = ui->textBrowser->toPlainText().mid(cursor.position() - 1, 1);
    qDebug() << key;
}
于 2013-11-12T20:51:43.677 回答