【问题标题】:Event QComboBox to Custom QLineEdit事件 QComboBox 到自定义 QLineEdit
【发布时间】:2018-11-14 16:47:07
【问题描述】:

问题:我在自定义QComboBox 内的QLineEdit 上有一个自定义事件,并且当我需要时,只有特定事件从QComboBox 传递到QLineEdit。我无法让标签被传递。

我希望当一个事件传递给QComboBox 时,它将传递给QComboBox->lineEdit()

QCustomCombo::QCustomCombo():
    m_lineEdit(new QCustomLineEdit)
{
    setEditable(true);
    setLineEdit(m_lineEdit);
}

bool QCustomCombo::event(QEvent * event)
{
    if(event->type() == QEvent::KeyPress)
    {
        QKeyEvent * keyEvent = static_cast<QKeyEvent *>(event);
        if(keyEvent->key() == Qt::Key_tab)
        {
            //pass to lineEdit();
            //I have tried 'return true/false and QWidget::event(event)'
            //I have also tried commenting out QCustomCombo::event, same problem
        }
    }
    return QWidget::event(event);
}

QCustomLineEdit

bool QCustomLineEdit::event(QEvent * event)
{
    if(event->type() == QEvent::KeyPress)
    {
        QKeyEvent * keyEvent = static_cast<QKeyEvent *>(event);
        if(keyEvent->key() == Qt::Key_tab)
        {
            //Do custom Stuff
            return true;
        }
        if(keyEvent->key() == Qt::Key_Right)
        {
            //Do custom Stuff
            return true;
        }
    }
    return QWidget::event(event);
}

QLineEdit 具有左右箭头和标签的自定义事件。只有箭头可以通过。但我无法让标签传递给它。

【问题讨论】:

    标签: c++ qt qt5 qcombobox qlineedit


    【解决方案1】:

    使用QApplication::notify

    bool QCustomCombo::event(QEvent * event)
    {
        if(event->type() == QEvent::KeyPress)
        {
            QKeyEvent * keyEvent = static_cast<QKeyEvent *>(event);
            if(keyEvent->key() == Qt::Key_Tab)
            {
                qApp->notify(m_lineEdit, event);
                return true;
            }
        }
        return QWidget::event(event);
    }
    

    【讨论】:

    • 如何访问 qApp 功能?我试过QCustomCombo : private QApplication,但这打破了我的connect() 行。 QCombo 位于由 main.cpp 创建的 mainwindow.cpp 内(main.cpp 是我拥有 QApplication 实例的位置)。
    • @DevilGale 不需要继承,只需包含标题:#include &lt;QApplication&gt;QApplication::instance() 是一个可以与 qApp 宏一起使用的单例。
    【解决方案2】:

    我希望当一个事件传递给 QComboBox 时,它将被传递给 QComboBox->lineEdit().

    installEventFilter() 是你的朋友。它允许对象A在另一个对象B上安装一个事件过滤器,这样在对象B的event(QEvent *)方法被调用之前,对象A的eventFilter(QObject *, QEvent *)方法将首先被调用,这样对象A就可以决定如何处理事件(以及之后是否应该将事件传递给对象 B)。

    您可以使用它,以便您的 CustomCombo 可以看到并响应事件,否则这些事件会直接转到 `QComboBox。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多