Lock a line in QTextEdit

≡放荡痞女 提交于 2019-12-12 05:17:49

问题


How can I lock a line(or a part of a line) in a "QTextEdit" control? I can do this: when I move the cursor position at that part of the line, the cursor will be moved automatically to the next first position that not belongs to that part of the line. Maybe you have antoher idea. Thank you!


回答1:


I would connect to the QTextEdit::cursorPositionChanged() and handle the movement there.

http://qt-project.org/doc/qt-4.8/qtextcursor.html#position

http://qt-project.org/doc/qt-4.8/qtextedit.html#textCursor

QObject::connect(myTextEdit, SIGNAL(cursorPositionChanged()), 
    this, SLOT(on_cursorPositionChanged()));

// ...

int lockedAreaStart = 15;
int lockedAreaEnd = 35;

// ...

void MyWidget::on_cursorPositionChanged()
{
    int lockedAreaMiddle = (lockedAreaEnd + lockedAreaStart)/2.;

    int cursorPosition = myTextEdit->textCursor().position();
    if(cursorPosition > lockedAreaStart && cursorPosition < lockedAreaEnd)
    {
        if(cursorPosition < lockedAreaMiddle)
        {
            // was to the left of the locked area, move it to the right
            myTextEdit->textCursor().setPosition(lockedAreaEnd);
        }
        else
        {
            // was to the right of the locked area, move it to the left
            myTextEdit->textCursor().setPosition(lockedAreaStart);
        }
    }
}

Instead of doing it this way, you could achieve a similar effect by subclassing QTextEdit, and reimplementing setPosition().

You may also need to add some error handling to the above code. And when text is inserted before your "locked line" you probably will need to modify your lockedAreaStart and your lockedAreaEnd.

Hope that helps.




回答2:


I think the best way to achieve that is to subclass QTextEdit and reimplement the event() method to handle all events that might change a locked line. Something like this:

class MyTextEdit : public QTextEdit 
{
    Q_OBJECT

public:

    bool event(QEvent *event) 
    {
        switch (event->type()) {
        case QEvent::KeyPress:
        case QEvent::EventThatMayChangeALine2:
        case QEvent::EventThatMayChangeALine3:
             if (tryingToModifyLockedLine(event)) {
                 return true; // true means "event was processed"
             }
        }

        return QTextEdit::event(event); // Otherwise delegate to QTextEdit
    }  
};

Besides QEvent::KeyPress there might be some other events that can change your text. For instance QEvent::Drop

For more information on events see:

http://doc.qt.digia.com/qt/eventsandfilters.html



来源:https://stackoverflow.com/questions/14567317/lock-a-line-in-qtextedit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!