簡體   English   中英

從QML獲得對文本光標的更多控制

[英]Get more control over text cursor from QML

在源代碼中,我注意到有相當全面的游標控制操作集:

enum MoveOperation {
    NoMove,
    Start,
    Up,
    StartOfLine,
    StartOfBlock,
    StartOfWord,
    PreviousBlock,
    PreviousCharacter,
    PreviousWord,
    Left,
    WordLeft,
    End,
    Down,
    EndOfLine,
    EndOfWord,
    EndOfBlock,
    NextBlock,
    NextCharacter,
    NextWord,
    Right,
    WordRight,
    NextCell,
    PreviousCell,
    NextRow,
    PreviousRow
};

相反,來自QtQuick.Controls 1.4的最新TextField ,光標位置顯示為一個簡單的整數,可以設置該整數,但不指定任何這些移動操作。 就是這樣。

在較早的TextEdit還有一些額外的東西,例如selectWord()moveCursorSelection(int position, SelectionMode mode) ,但是mode僅限於選擇字符或單詞。

更糟糕的是,稀疏的現有API並沒有真正提供手動重新實現大多數模式所需的功能。

因此,thins使我想到一個問題,即如何以最直接,最不引人注目的方式獲得QML中的所有功能?

更新:

實際上,有一種更明顯,更不那么麻煩的方式來獲得該功能,即通過將假事件發布到所需的文本編輯中。 這樣做的好處是不需要使用私有API,從而避免了所有潛在的構建和兼容性復雜性:

void postKeyEvent(Qt::Key k, QObject * o, bool sh = false, bool ct = false, bool al = false) {
  uint mod = Qt::NoModifier;
  if (sh) mod |= Qt::ShiftModifier;
  if (ct) mod |= Qt::ControlModifier;
  if (al) mod |= Qt::AltModifier;
  QCoreApplication::postEvent(o, new QKeyEvent(QEvent::KeyPress, k, (Qt::KeyboardModifier)mod));
  QTimer::singleShot(50, [=]() { QCoreApplication::postEvent(o, new QKeyEvent(QEvent::KeyRelease, k, (Qt::KeyboardModifier)mod)); });
}

現在,我終於可以在觸摸設備上使用自定義的虛擬鍵盤來獲得所有需要的光標控制內容。


這是一個實際可行的簡單解決方案...如果您設法構建它,則構建它會遇到一些奇怪的問題

#include <QtQuick/private/qquicktextedit_p.h>
#include <QtQuick/private/qquicktextedit_p_p.h>
#include <QtQuick/private/qquicktextcontrol_p.h>

class CTextEdit : public QQuickTextEdit {
    Q_OBJECT
  public:
    CTextEdit(QQuickItem * p = 0) : QQuickTextEdit(p) {}
  public slots:
    void cursorOp(int mode) {
      QQuickTextEditPrivate * ep = reinterpret_cast<QQuickTextEditPrivate *>(d_ptr.data());
      QTextCursor c = ep->control->textCursor();
      c.movePosition((QTextCursor::MoveOperation)mode);
      ep->control->setTextCursor(c);
    }
};

顯然,它使用私有頭,這有兩個含義:

  • 您將必須將quick-privte模塊添加到PRO文件中
  • 私人信息可能會發生變化,包括重大更改,因為此友好消息不斷提醒您:

_

Project MESSAGE: This project is using private headers and will therefore be tied to this specific Qt module build version.
Project MESSAGE: Running this project against other versions of the Qt modules may crash at any arbitrary point.
Project MESSAGE: This is not a bug, but a result of using Qt internals. You have been warned!

從好的方面來說,它就像是一種魅力。 IMO認為,功能應該作為公共API的一部分開始可用,它非常有用,當然,隱藏起來沒有什么意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM