QLineEdit:显示已处理的文本,而不是输入的文本,但保留它(自定义回显模式)

2022-02-27 00:00:00 qt5 qt qlineedit c++
我希望QLineEdit不显示输入的文本,而是显示已处理的版本,同时保留原始文本,并在通过text()请求时将其返回。就像密码回显模式一样,但我不希望每个字符都被屏蔽。我想虚拟化空间:

例如,当输入some text with spaces in between时,应显示some・text・with・spaces・in・between,以便用户可以看到空格。就像您在LibreOffice中激活ó符号一样。

QLineEdit::displayText(),但不能设置,只能读取。另外,echoMode只能通过枚举设置,在设置了EchoMode::Password的情况下,处理似乎发生在QLineEdit的私有函数中,所以我也不能重写某些处理函数。

这可能吗?


解决方案

imho,使用QLineEdit很难做到这一点。

但是,通过配置QTextDocumentQTextEdit

,使用QTextEdit相当简单
class TextEdit : public QTextEdit
{
    Q_OBJECT
public:
        explicit TextEdit(QWidget* parent=nullptr): QTextEdit (parent)
        {
                QTextDocument* doc = new QTextDocument(this);
                setDocument(doc);
                QTextOption option;
                option.setFlags(QTextOption::ShowLineAndParagraphSeparators | QTextOption::ShowTabsAndSpaces);
                doc->setDefaultTextOption(option);
        }
};

然后,您必须配置TextEdit以获得与QLineEdit相同的行为(即一行,没有滚动条等)。

作为良好开端的快速示例:

class OneLineTextEdit : public QTextEdit
{
    Q_OBJECT
public:
        explicit OneLineTextEdit(QWidget* parent=nullptr): QTextEdit (parent)
        {
                setTabChangesFocus(true);
                setWordWrapMode(QTextOption::NoWrap);
                // No scrollbars
                setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
                setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
                setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

                // One line only
                setFixedHeight(sizeHint().height());

                // Show the space/tabs/return
                QTextDocument* doc = new QTextDocument(this);
                setDocument(doc);
                QTextOption option;
                option.setFlags(QTextOption::ShowLineAndParagraphSeparators | QTextOption::ShowTabsAndSpaces);
                doc->setDefaultTextOption(option);
        }

    // We don't want to write more than one line
    void keyPressEvent(QKeyEvent *event)
    {
        if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
                return event->ignore();
        return QTextEdit::keyPressEvent(event);
    }

    // Don't display more than one line
    QSize sizeHint() const
    {
        QFontMetrics const fm(font());
        int const h = qMax(fm.height(), 14) + 4;
        int const w = fm.width(QLatin1Char('x')) * 17 + 4;
        QStyleOption opt;
        opt.initFrom(this);
        // Use the current app style to find the size of a real QLineEdit
        return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
                expandedTo(QApplication::globalStrut()), this));
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    OneLineTextEdit *editor = new OneLineTextEdit();
    editor->show();

    return app.exec();
};

相关文章