问题描述
仅在某些情况下可以触发textChanged信号吗?例如触发它以插入文本,插入空格字符但不退格?
每次文本更改时,我都会运行QTextEdit中的键入字符,并根据结果突出显示在后台只读QTextEdit中的文本,该文本用作始终在线的占位符文本,供用户在键入时查看。如果用户输入有误,则该字符将突出显示为红色,并在纠正错误后重置为其初始背景色。按下退格键时会出现问题,因为它被注册为错误,因此前一个字符也被突出显示为红色。
void Widget::onTextChanged()
{
QChar c;
QString txt_contents = txtedit_->toPlainText();
if(txt_contents.isEmpty()){
c = '\0';
//reset text display
txtdisplay_->clear();
txtdisplay_->append(*label_text_);
}
else
c = txtedit_->toPlainText().back();
if(!texteditq_->isEmpty()){
if(c == texteditq_->head()){
//refresh text display
correct_++;
txtdisplay_->clear();
txtdisplay_->append(*label_text_);
//remove character that was used for the successful check from the
//queue
texteditq_->dequeue();
}else{
//set backgroud color to red for errors
fmt_->setBackground(Qt::red);
if(!txtedit_->toPlainText().isEmpty()){
//move cursor to the end of the editor,where the error is and save
//the position the error occurs at
c_edit_->movePosition(QTextCursor::End);
quint32 error_pos = c_edit_->position();
//move the cursor in the display for the background text and
//use the KeepAnchor move mode to highlight the misspelled char
c_display_->setPosition(error_pos-1,QTextCursor::MoveAnchor);
c_display_->setPosition(error_pos,QTextCursor::KeepAnchor);
//apply formating to that character
c_display_->setCharFormat(*fmt_);
}
}
}
}
解决方法
根据OP的请求,我正在发布一个名为CustomTextEdit
的类的解决方案,该类继承了QTextEdit
。它正在钩接到keyPressEvent()
并检查按下的键。如果不是Backspace,则将发出自定义信号keyPressed()
。
class CustomTextEdit : public QTextEdit {
Q_OBJECT
public:
explicit CustomTextEdit(QWidget *parent = nullptr) : QTextEdit(parent) {}
signals:
void keyPressed();
protected:
void keyPressEvent(QKeyEvent *e) override {
if (e->key() != Qt::Key_Backspace) {
emit keyPressed();
}
QTextEdit::keyPressEvent(e);
}
};