【问题标题】:Qt C++ how to use keyPressEvent for a QWidget within a classQt C ++如何在类中为QWidget使用keyPressEvent
【发布时间】:2013-11-12 18:33:26
【问题描述】:

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

这是我的代码:

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

};

在 customdialog.cpp 中:

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

如何使此类中的所有小部件都使用相同的 keyPressEvent?

【问题讨论】:

    标签: c++ qt events


    【解决方案1】:

    您可以通过为 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。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2011-12-14
        • 2016-11-25
        • 2011-02-13
        • 2014-08-17
        • 1970-01-01
        • 1970-01-01
        • 2015-01-21
        • 2018-01-10
        • 1970-01-01
        相关资源
        最近更新 更多