开发者

QPlainTextEdit - change shift+return behaviour

I use a QPlainTextEdit for a code editor that also shows line numbers. But when I press shift+return a the editor makes a开发者_Python百科 break, but the line number don't increases.

I think in html it would just be a <br/> instead of a new <p> tag...

Have a look at the screenshot...

QPlainTextEdit - change shift+return behaviour


You should probably be using QTextEdit since this is rich text we're talking about.

Override virtual void keyPressEvent ( QKeyEvent * e ). You can call QTextEdit::keyPressEvent in the implementation to delegate non-special cases.


You can, actually, use object with eventFilter and installEventFilter function.

#ifndef SHIFTENTERFILTER_H
#define SHIFTENTERFILTER_H

#include <QObject>
#include <QEvent>
#include <QKeyEvent>

class ShiftEnterFilter : public QObject
{
    protected:
        virtual bool eventFilter(QObject *, QEvent *event) {
            if(event -> type() == QEvent::KeyPress)
            {
                QKeyEvent *keyEvent = static_cast <QKeyEvent> (event);

                if((keyEvent -> modifiers() & Qt::ShiftModifier) && ((keyEvent -> key() == Qt::Key_Enter) || (keyEvent -> key() == Qt::Key_Return)))
                    return true;
            }

            return false;
        }      
    public:
        ShiftEnterFilter(QObject *parent = 0) : QObject(parent) {}
};  

#endif 

Just install this filter to your QPlainTextEdit

// code
ui -> plainTextEdit -> installEventFilter(new ShiftEnterFilter(this));
// code


Try this (CodeEdit inherits QPlainTextEdit):

/**
 * override keyPressEvent, change behaviour of shift + enter(return)
 * @brief CodeEdit::keyPressEvent
 * @param event
 */
void CodeEdit::keyPressEvent(QKeyEvent *event)
{
    QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);

    // disable shift + enter(return)
    if ((keyEvent->modifiers() & Qt::ShiftModifier) && (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return)) {
        event->ignore();
        return;
    }
    QPlainTextEdit::keyPressEvent(event);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜