簡體   English   中英

添加帶有 QSyntaxHighlighter 和 QTextCharFormat 的 ToolTip

[英]Add a ToolTip with a QSyntaxHighlighter and a QTextCharFormat

我正在嘗試在 Qt 中創建一個小語法熒光筆,並且我想在用戶將其懸停時顯示一個帶有錯誤描述的工具提示。

(我正在繼承 QSyntaxHighlighter)

我已經嘗試過QTextCharFormat::setToolTip setToolTip function,但它不起作用:/ 文本按預期帶有紅色下划線,但是當我在它上面使用 hover 時沒有顯示工具提示。

我錯過了什么? 還是我應該使用其他方法?

void CodeHighlighter::highlightBlock(const QString &text)
{
    _errorFormat.setProperty(QTextFormat::TextUnderlineStyle, QTextCharFormat::SpellCheckUnderline);
    _errorFormat.setProperty(QTextFormat::TextUnderlineColor, QColor(Qt::red));
    if (!isLineValid(text.toStdString())) {

        // The following line does not work !
        _errorFormat.setToolTip(QString::fromStdString(getLastError()));

        setFormat(0, text.length(), _errorFormat);
    }
    for (const HighlightingRule &rule : qAsConst(_highlightingRules)) {
        QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
        while (matchIterator.hasNext()) {
            QRegularExpressionMatch match = matchIterator.next();
            QTextCharFormat format = this->format(match.capturedStart());
            format.merge(rule.format);
            setFormat(match.capturedStart(), match.capturedLength(), format);
        }
    }
}

您可以通過覆蓋QEvent::ToolTip的處理並自己進行查找來使其工作。

我沒有時間在 C++ 中重寫我的完整答案,但是:

  • 這個 SO 答案有 C++ 代碼用於執行覆蓋但不是查找。 (基本上,在QTextEditQPlainTextEdit上,您setMouseTracking(True) ,覆蓋event方法,並移交給默認實現,除非event->type() == QEvent::ToolTip 。該問題的另一個答案點如果您使用它們,您還需要更正邊距。)
  • 這篇 QtCenter 帖子有 C++ 代碼,用於在 C++ 中查找應用熒光筆的格式......盡管它確實使用了一種已棄用的方法。 (它的要點是,在現代 Qt 中,您需要使用cursorForPosition ,然后使用.block().layout()->formats()並迭代,將偏移量與光標的position()進行比較。additionalFormats additionalFormats()是不推薦使用的方法和formats()是現代的。)
  • 我寫的這個 SO 答案是一個完整的、可運行的示例,它演示了將語法檢查信息公開為工具提示......它只是在 Python 中針對 PyQt 編寫的。

暫無
暫無

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

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