diff --git a/src/plugins/qmldesigner/components/texteditor/texteditorwidget.cpp b/src/plugins/qmldesigner/components/texteditor/texteditorwidget.cpp index 9b5dc32ff8e..ee1a749a492 100644 --- a/src/plugins/qmldesigner/components/texteditor/texteditorwidget.cpp +++ b/src/plugins/qmldesigner/components/texteditor/texteditorwidget.cpp @@ -26,6 +26,7 @@ #include "texteditorwidget.h" #include +#include #include @@ -42,12 +43,20 @@ TextEditorWidget::TextEditorWidget(TextEditorView *textEditorView) : QWidget() QBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); + m_updateSelectionTimer.setSingleShot(true); + m_updateSelectionTimer.setInterval(200); + + connect(&m_updateSelectionTimer, &QTimer::timeout, this, &TextEditorWidget::updateSelectionByCursorPosition); setStyleSheet(Theming::replaceCssColors(QString::fromUtf8(Utils::FileReader::fetchQrc(QLatin1String(":/qmldesigner/scrollbar.css"))))); } void TextEditorWidget::setTextEditor(TextEditor::BaseTextEditor *textEditor) { m_textEditor.reset(textEditor); layout()->addWidget(textEditor->editorWidget()); + + + connect(textEditor->editorWidget(), &QPlainTextEdit::cursorPositionChanged, + &m_updateSelectionTimer, static_cast(&QTimer::start)); } QString TextEditorWidget::contextHelpId() const @@ -55,4 +64,20 @@ QString TextEditorWidget::contextHelpId() const return m_textEditorView->contextHelpId(); } +void TextEditorWidget::updateSelectionByCursorPosition() +{ + /* Because of the timer we have to be careful. */ + if (!m_textEditorView->model()) + return; + + const int cursorPosition = m_textEditor->editorWidget()->textCursor().position(); + RewriterView *rewriterView = m_textEditorView->model()->rewriterView(); + + if (rewriterView) { + ModelNode modelNode = rewriterView->nodeAtTextCursorPosition(cursorPosition); + if (modelNode.isValid()) + m_textEditorView->setSelectedModelNode(modelNode); + } +} + } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/texteditor/texteditorwidget.h b/src/plugins/qmldesigner/components/texteditor/texteditorwidget.h index 5093cfe7ed6..84cd7297f92 100644 --- a/src/plugins/qmldesigner/components/texteditor/texteditorwidget.h +++ b/src/plugins/qmldesigner/components/texteditor/texteditorwidget.h @@ -27,6 +27,7 @@ #include #include +#include #include @@ -51,8 +52,11 @@ public: QString contextHelpId() const; private: + void updateSelectionByCursorPosition(); + std::unique_ptr m_textEditor; QPointer m_textEditorView; + QTimer m_updateSelectionTimer; }; } // namespace QmlDesigner