I want to convert all lowercase characters as I type to uppercase in a QPlainTextEdit
. In a QLineEdit
I do the same via a validator, but there seems to be no validator for QPlainTextEdit
.
I have tried ui->pte_Route->setInputMethodHints(Qt::ImhUppercaseOnly);
but it does nothing, most likely using it wrong.
Any better option as using my "own" class?
A quick test using an event filter seems to work reasonably well...
class plain_text_edit: public QPlainTextEdit {
using super = QPlainTextEdit;
public:
explicit plain_text_edit (QWidget *parent = nullptr)
: super(parent)
{
installEventFilter(this);
}
protected:
virtual bool eventFilter (QObject *obj, QEvent *event) override
{
if (event->type() == QEvent::KeyPress) {
if (auto *e = dynamic_cast<QKeyEvent *>(event)) {
/*
* If QKeyEvent::text() returns an empty QString then let normal
* processing proceed as it may be a control (e.g. cursor movement)
* key. Otherwise convert the text to upper case and insert it at
* the current cursor position.
*/
if (auto text = e->text(); !text.isEmpty()) {
insertPlainText(text.toUpper());
/*
* return true to prevent further processing.
*/
return true;
}
}
}
return super::eventFilter(obj, event);
}
If it does work sufficiently well then the event filter code can always be pulled out separately for re-use.