强制QPlainTextEdit大写字符

时间:2019-04-12 17:16:49

标签: c++ qt qplaintextedit

我想在QPlainTextEdit中键入时将所有小写字符转换为大写。在QLineEdit中,我通过验证器进行了同样的操作,但是似乎没有QPlainTextEdit的验证器。

我尝试过ui->pte_Route->setInputMethodHints(Qt::ImhUppercaseOnly);,但是它什么也没做,很可能使用不正确。

有没有比使用“自己的”课程更好的选择了?

3 个答案:

答案 0 :(得分:1)

使用事件过滤器进行快速测试似乎效果不错...

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

如果运行良好,则始终可以单独提取事件过滤器代码以供重复使用。

答案 1 :(得分:1)

为这样一个简单的任务使用事件过滤器似乎不是一个好主意,因为您被迫实施继承QPlainTextEdit的单独类或创建一些充当过滤器的单独类。相反,您还可以执行以下操作:

// Note. This is just a sample. Assume that 'this' is context of some class (e.g. class implementing QDialog/QMainWindow)
auto lineEdit = new QLineEdit();
/*
Here, you can use also &QLineEdit::textChanged, and it would not cause any stackoverflow,
since Qt is pretty optimized here, i.e. if text does not change actually (value of QString
remains the same), Qt won't fire the signal. However, it is probably better to use
&QLineEdit::textEdited, since you expect the user to enter the text.
*/
connect(lineEdit, &QLineEdit::textEdited, this, [lineEdit](const QString& text)
{
    lineEdit->setText(text.toUpper());
});

换句话说,您可以通过Qt提供给我们的简单信号和时隙机制来实现所需的相同行为。如果可以通过标准框架机制实现所需的功能,则应尝试执行此操作,而不要尝试实现可能导致您甚至没有意识到的问题的事件过滤器。请记住,事件过滤器是Qt提供的另一种机制,它使您有更多的自由去做自己想做的事,但同时也必须承担更多的极端情况。

答案 2 :(得分:1)

我遇到了 eventFilter 方法的问题,我使用了一个更简单的解决方案:

protected:
    void keyPressEvent(QKeyEvent* e) override {
        if (!e->text().isNull() && !e->text().isEmpty() &&
            e->key() >= Qt::Key_A && e->key() <= Qt::Key_Z)
        {
            insertPlainText(e->text().toUpper());
        }
        else
            QPlainTextEdit::keyPressEvent(e);
    }

我正在使用从 QPlainTextEdit 继承的 Qt 示例中的 CodeEditor 类。