开发者

Qt handling of keyevents

开发者 https://www.devze.com 2023-02-15 14:42 出处:网络
I am trying to write a console widget to my graphic program in C++. I am making the console widget a child widget to the widget acting as a main window. The console is a QDockWidget that holds a QText

I am trying to write a console widget to my graphic program in C++. I am making the console widget a child widget to the widget acting as a main window. The console is a QDockWidget that holds a QTextEdit. What I want to do is to handle events when the Return key is pressed from the ConsoleWidget and then handle the command, all other key events should be handleded by the QTextEdit. The problem is that I am not able to catch any key events except events like Command and Shift keys... Any ideas?

This is the code for the console:

class ConsoleWidget : public QDockWidget
{
public:
    ConsoleWidget( const QString& sTitle, QWidget* pParent = 0, Qt::WindowFlags nFlags = 0 );
    ~ConsoleWidget();

protected:
    void keyPressEvent( QKeyEvent* pEvent );
    void keyReleaseEvent( QKeyEvent* pEvent );

private:
    QTextEdit* m_pTextArea;
};


ConsoleWidget::ConsoleWid开发者_如何学运维get( const QString& sTitle, QWidget* pParent, Qt::WindowFlags nFlags ) :
        QDockWidget( sTitle, pParent, nFlags )
{
    setFocusPolicy( Qt::StrongFocus );
    m_pTextArea = new QTextEdit( this );
    setWidget( m_pTextArea );
}

ConsoleWidget::~ConsoleWidget()
{
    // Qt is taking ownership of pTextWidget... (I think)
}

void ConsoleWidget::keyPressEvent( QKeyEvent* pEvent )
{
    if( pEvent->key() & Qt::Key_Return )
    {
        int i = 666;
    }
    else
    {
        pEvent->setAccepted( false );
        // TODO Should I do this if not handling the event?
        //QDockWidget::keyPressEvent( pEvent );
    }
}

void ConsoleWidget::keyReleaseEvent( QKeyEvent* pEvent )
{
    QDockWidget::keyReleaseEvent( pEvent );
}


You need to subclass QTextEdit and override the keyPressEvent method there. Remember the QTextEdit class will be consuming most key events and so they will not be getting propagated up to the parent dock widget.

Alternatively you could install an event filter. The docs give a good example. In your case your custom dock widget class could be the event filter for the QTextEdit so that your logic is all in that class.

0

精彩评论

暂无评论...
验证码 换一张
取 消