[英]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++ 中重寫我的完整答案,但是:
QTextEdit
或QPlainTextEdit
上,您setMouseTracking(True)
,覆蓋event
方法,並移交給默認實現,除非event->type() == QEvent::ToolTip
。該問題的另一個答案點如果您使用它們,您還需要更正邊距。)cursorForPosition
,然后使用.block().layout()->formats()
並迭代,將偏移量與光標的position()
進行比較。additionalFormats additionalFormats()
是不推薦使用的方法和formats()
是現代的。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.