Home > OS >  I want to know the line number in editText where the cursor is
I want to know the line number in editText where the cursor is

Time:12-15

I want to know the line number in editText where the cursor is. How do I get that?

I checked the documentation, and there's no ps:Is the textedit QML,not QTextEdit

CodePudding user response:

You have to use textDocument and cursorPosition properties in :

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickTextDocument>
#include <QTextBlock>

class Helper: public QObject{
    Q_OBJECT
public:
    Q_INVOKABLE int currentLineNumber(QQuickTextDocument *textDocument, int cursorPosition){
        if(QTextDocument * td = textDocument->textDocument()){
            QTextBlock tb = td->findBlock(cursorPosition);
            return tb.blockNumber();
        }
        return -1;
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    Helper helper;
    engine.rootContext()->setContextProperty("helper", &helper);
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

main.qml

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 640
    height: 480
    visible: true

    TextEdit{
        id: textEdit
        anchors.fill: parent
        onCursorPositionChanged: function(){
            let line = helper.currentLineNumber(textEdit.textDocument, textEdit.cursorPosition);
            console.log(line);
        }
    }
}
  • Related