2

Qt 实现文字输入框,带字数限制 - 师从名剑山

 2 years ago
source link: https://www.cnblogs.com/codegb/p/16120260.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Qt 实现文字输入框,带字数限制

核心的点在于,限制输入的字数;主要的方法为创建一个组合窗口

img

  1. textChanged 这个信号,会在你输入字符之后发射,可以连接这个信号,在发射了信号之后,去获取当前QTextEdit里的内容,获取数量,然后根据最大数量,来选择是不是需要截取文本;

  2. 光标的移动的问题。在进行插入时,光标要时刻保持在当前位置。

  3. 文字内容的行高。这里请看Qt设置QTextEdit的行高_师从名剑山的博客-CSDN博客_qt qtextedit 高度


// 首先连接信号
connect(ui->textEdit, &QTextEdit::textChanged,
            this, &LimitTextEdit::slot_handleInput);

void LimitTextEdit::slot_handleInput()
{
    auto textEdit = static_cast<QTextEdit*>(sender());

    int currentNum = textEdit->toPlainText().length();
    // 判断是不是超出了字数限制
    if (currentNum > m_maxWordNum) {
        QString text = textEdit->toPlainText();
        text = text.mid(0, m_maxWordNum);
        int position = textEdit->textCursor().position();

        textEdit->setText(text);

        // 获取光标位置
        QTextCursor cursor = textEdit->textCursor();
        if (position > m_maxWordNum) {
            // 如果当前输入位置为末尾的话,就直接跳到最后一个字符。
            position = m_maxWordNum;
        }
        cursor.setPosition(position);
        textEdit->setTextCursor(cursor);
        currentNum = m_maxWordNum;
    }

    ui->labelCurrentNum->setNum(currentNum);
}

代码下载请看此处LimitTextEdit


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK