我想知道光标所在的editText中的行号

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

我想知道光标所在的editText中的行号。我如何获得它?

我查了文档,没有 ps:Is textedit QML,不是 QTextEdit

你必须使用 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);
        }
    }
}