在QTextEdit中锁定一行 [英] Lock a line in QTextEdit

查看:357
本文介绍了在QTextEdit中锁定一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在"QTextEdit"控件中锁定一行(或一行的一部分)?我可以这样做:当我将光标位置移动到该行的那部分时,光标将自动移动到不属于该行那部分的下一个第一个位置.也许您有另一个主意. 谢谢!

我认为实现此目标的最佳方法是将QTextEdit子类化并重新实现event()方法以处理可能更改锁定行的所有事件.像这样:

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
    }  
};

除了QEvent::KeyPress之外,还有其他一些事件可能会更改您的文本.例如QEvent::Drop

有关事件的更多信息,请参见:

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

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!

解决方案

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

这篇关于在QTextEdit中锁定一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆