Qt C++如何在类中使用 keyPressEvent 进行 QWidget

Qt C++ how to use keyPressEvent for a QWidget within a class

本文关键字:keyPressEvent 进行 QWidget C++ Qt      更新时间:2023-10-16

我正在尝试使用keyPressEvent,但它仅在窗口具有焦点而不是任何QWidgets时才起作用。

这是我的代码:

在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);
};

在自定义对话框中.cpp:

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

如何使此类中的所有小部件使用相同的键按事件?

您可以通过将事件过滤器安装到自定义对话框的每个子级来解决您的问题:

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。

我最终决定在这种情况下不使用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;
}