Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtooltip.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include <QtWidgets/private/qtwidgetsglobal_p.h>
6
7#include <qapplication.h>
8#include <qevent.h>
9#include <qstyle.h>
10#include <qstyleoption.h>
11#include <qstylepainter.h>
12#if QT_CONFIG(effects)
13#include <private/qeffects_p.h>
14#endif
15#include <qpa/qplatformscreen.h>
16#include <qpa/qplatformcursor.h>
17#if QT_CONFIG(style_stylesheet)
18#include <private/qstylesheetstyle_p.h>
19#endif
20#include <qpa/qplatformwindow.h>
21#include <qpa/qplatformwindow_p.h>
22
23#include <QtWidgets/private/qlabel_p.h>
24#include <QtGui/private/qhighdpiscaling_p.h>
25#include <qtooltip.h>
26#include <QtWidgets/private/qtooltip_p.h>
27
28using namespace std::chrono_literals;
29
30QT_BEGIN_NAMESPACE
31
32using namespace Qt::StringLiterals;
33
34/*!
35 \class QToolTip
36
37 \brief The QToolTip class provides tool tips (balloon help) for any
38 widget.
39
40 \ingroup helpsystem
41 \inmodule QtWidgets
42
43 The tip is a short piece of text reminding the user of the
44 widget's function. It is drawn immediately below the given
45 position in a distinctive black-on-yellow color combination. The
46 tip can be any \l{QTextEdit}{rich text} formatted string.
47
48 \note Since QToolTip is rich-text enabled, any content that originates outside the trust
49 boundary of the application should be preprocessed through a function such as
50 QString::toHtmlEscaped().
51
52 Rich text displayed in a tool tip is implicitly word-wrapped unless
53 specified differently with \c{<p style='white-space:pre'>}.
54
55 UI elements that are created via \l{QAction} use the tooltip property
56 of the QAction, so for most interactive UI elements, setting that
57 property is the easiest way to provide tool tips.
58
59 \snippet tooltips/main.cpp action_tooltip
60
61 For any other widgets, the simplest and most common way to set
62 a widget's tool tip is by calling its QWidget::setToolTip() function.
63
64 \snippet tooltips/main.cpp static_tooltip
65
66 It is also possible to show different tool tips for different
67 regions of a widget, by using a QHelpEvent of type
68 QEvent::ToolTip. Intercept the help event in your widget's \l
69 {QWidget::}{event()} function and call QToolTip::showText() with
70 the text you want to display.
71
72 \snippet tooltips/main.cpp dynamic_tooltip
73
74 If you are calling QToolTip::hideText(), or QToolTip::showText()
75 with an empty string, as a result of a \l{QEvent::}{ToolTip}-event you
76 should also call \l{QEvent::}{ignore()} on the event, to signal
77 that you don't want to start any tooltip specific modes.
78
79 Note that, if you want to show tooltips in an item view, the
80 model/view architecture provides functionality to set an item's
81 tool tip; e.g., the QTableWidgetItem::setToolTip() function.
82 However, if you want to provide custom tool tips in an item view,
83 you must intercept the help event in the
84 QAbstractItemView::viewportEvent() function and handle it yourself.
85
86 The default tool tip color and font can be customized with
87 setPalette() and setFont(). When a tooltip is currently on
88 display, isVisible() returns \c true and text() the currently visible
89 text.
90
91 \note Tool tips use the inactive color group of QPalette, because tool
92 tips are not active windows.
93
94 \sa QWidget::toolTip, QAction::toolTip
95*/
96
97static QTipLabel *qTipLabel = nullptr;
98
99QTipLabel::QTipLabel(const QString &text, QPoint pos, QWidget *w,
100 std::chrono::milliseconds displayTime)
101 : QLabel(w, Qt::ToolTip | Qt::BypassGraphicsProxyWidget)
102#if QT_CONFIG(style_stylesheet)
103 , styleSheetParent(nullptr)
104#endif
105 , widget(nullptr)
106 , fadingOut(false)
107{
108 setTextFormat(Qt::AutoText);
109
110 delete qTipLabel;
111 qTipLabel = this;
112 setForegroundRole(QPalette::ToolTipText);
113 setBackgroundRole(QPalette::ToolTipBase);
114 setPalette(QToolTip::palette());
115 ensurePolished();
116 setMargin(1 + style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, nullptr, this));
117 setFrameStyle(QFrame::NoFrame);
118 setAlignment(Qt::AlignLeft);
119 setIndent(1);
120 qApp->installEventFilter(this);
121 setWindowOpacity(style()->styleHint(QStyle::SH_ToolTipLabel_Opacity, nullptr, this) / 255.0);
122 setMouseTracking(true);
123 reuseTip(text, displayTime, pos);
124}
125
126void QTipLabel::restartExpireTimer(std::chrono::milliseconds displayTime)
127{
128 Q_D(const QLabel);
129 std::chrono::milliseconds time;
130 if (displayTime > 0ms) {
131 time = displayTime;
132 } else {
133 const qsizetype textLength =
134 d->needTextControl() ? d->control->toPlainText().size() : text().size();
135 time = std::chrono::milliseconds(10000 + 40 * qMax(0, textLength - 100));
136 }
137 expireTimer.start(time, this);
138 hideTimer.stop();
139}
140
141void QTipLabel::reuseTip(const QString &text, std::chrono::milliseconds displayTime, QPoint pos)
142{
143#if QT_CONFIG(style_stylesheet)
144 if (styleSheetParent){
145 disconnect(styleSheetParent, &QWidget::destroyed,
146 this, &QTipLabel::styleSheetParentDestroyed);
147 styleSheetParent = nullptr;
148 }
149#endif
150
151 setWordWrap(Qt::mightBeRichText(text));
152 setText(text);
153 updateSize(pos);
154 restartExpireTimer(displayTime);
155}
156
157void QTipLabel::updateSize(const QPoint &pos)
158{
159 d_func()->setScreenForPoint(pos);
160 // Ensure that we get correct sizeHints by placing this window on the right screen.
161 QFontMetrics fm(font());
162 QSize extra(1, 0);
163 // Make it look good with the default ToolTip font on Mac, which has a small descent.
164 if (fm.descent() == 2 && fm.ascent() >= 11)
165 ++extra.rheight();
166 QSize sh = sizeHint();
167 const QSize screenSize = getTipScreen(pos, this)->size();
168 if (!wordWrap() && sh.width() > screenSize.width()) {
169 setWordWrap(true);
170 sh = sizeHint();
171 }
172 resize((sh + extra).boundedTo(screenSize));
173}
174
175void QTipLabel::paintEvent(QPaintEvent *ev)
176{
177 QStylePainter p(this);
178 QStyleOptionFrame opt;
179 opt.initFrom(this);
180 p.drawPrimitive(QStyle::PE_PanelTipLabel, opt);
181 p.end();
182
183 QLabel::paintEvent(ev);
184}
185
186void QTipLabel::resizeEvent(QResizeEvent *e)
187{
188 QStyleHintReturnMask frameMask;
189 QStyleOption option;
190 option.initFrom(this);
191 if (style()->styleHint(QStyle::SH_ToolTip_Mask, &option, this, &frameMask))
192 setMask(frameMask.region);
193
194 QLabel::resizeEvent(e);
195}
196
197void QTipLabel::mouseMoveEvent(QMouseEvent *e)
198{
199 if (!rect.isNull()) {
200 QPointF pos = e->globalPosition();
201 if (widget)
202 pos = widget->mapFromGlobal(pos);
203 if (!rect.contains(pos.toPoint()))
204 hideTip();
205 }
206 QLabel::mouseMoveEvent(e);
207}
208
209QTipLabel::~QTipLabel()
210{
211 qTipLabel = nullptr;
212}
213
214void QTipLabel::hideTip()
215{
216 if (!hideTimer.isActive())
217 hideTimer.start(300, this);
218}
219
220void QTipLabel::hideTipImmediately()
221{
222 close(); // to trigger QEvent::Close which stops the animation
223 deleteLater();
224}
225
226void QTipLabel::setTipRect(QWidget *w, const QRect &r)
227{
228 if (Q_UNLIKELY(!r.isNull() && !w)) {
229 qWarning("QToolTip::setTipRect: Cannot pass null widget if rect is set");
230 return;
231 }
232 widget = w;
233 rect = r;
234}
235
236void QTipLabel::timerEvent(QTimerEvent *e)
237{
238 if (e->timerId() == hideTimer.timerId()
239 || e->timerId() == expireTimer.timerId()){
240 hideTimer.stop();
241 expireTimer.stop();
242 hideTipImmediately();
243 }
244}
245
246bool QTipLabel::eventFilter(QObject *o, QEvent *e)
247{
248 switch (e->type()) {
249#ifdef Q_OS_MACOS
250 case QEvent::KeyPress:
251 case QEvent::KeyRelease: {
252 const int key = static_cast<QKeyEvent *>(e)->key();
253 // Anything except key modifiers or caps-lock, etc.
254 if (key < Qt::Key_Shift || key > Qt::Key_ScrollLock)
255 hideTipImmediately();
256 break;
257 }
258#endif
259 case QEvent::Leave:
260 hideTip();
261 break;
262
263
264#if defined (Q_OS_QNX) || defined (Q_OS_WASM) // On QNX the window activate and focus events are delayed and will appear
265 // after the window is shown.
266 case QEvent::WindowActivate:
267 case QEvent::FocusIn:
268 return false;
269 case QEvent::WindowDeactivate:
270 if (o != this)
271 return false;
272 hideTipImmediately();
273 break;
274 case QEvent::FocusOut:
275 if (reinterpret_cast<QWindow*>(o) != windowHandle())
276 return false;
277 hideTipImmediately();
278 break;
279#else
280 case QEvent::WindowActivate:
281 case QEvent::WindowDeactivate:
282 case QEvent::FocusIn:
283 case QEvent::FocusOut:
284#endif
285 case QEvent::MouseButtonPress:
286 case QEvent::MouseButtonRelease:
287 case QEvent::MouseButtonDblClick:
288 case QEvent::Wheel:
289 hideTipImmediately();
290 break;
291
292 case QEvent::MouseMove:
293 if (o == widget && !rect.isNull() && !rect.contains(static_cast<QMouseEvent*>(e)->position().toPoint()))
294 hideTip();
295 break;
296 default:
297 break;
298 }
299 return false;
300}
301
302QScreen *QTipLabel::getTipScreen(const QPoint &pos, QWidget *w)
303{
304 QScreen *guess = w ? w->screen() : QGuiApplication::primaryScreen();
305 QScreen *exact = guess->virtualSiblingAt(pos);
306 return exact ? exact : guess;
307}
308
309void QTipLabel::placeTip(const QPoint &pos, QWidget *w)
310{
311#if QT_CONFIG(style_stylesheet)
312 if (testAttribute(Qt::WA_StyleSheet) || (w && qt_styleSheet(w->style()))) {
313 //the stylesheet need to know the real parent
314 qTipLabel->setProperty("_q_stylesheet_parent", QVariant::fromValue(w));
315 //we force the style to be the QStyleSheetStyle, and force to clear the cache as well.
316 qTipLabel->setStyleSheet("/* */"_L1);
317
318 // Set up for cleaning up this later...
319 qTipLabel->styleSheetParent = w;
320 if (w) {
321 connect(w, &QWidget::destroyed,
322 qTipLabel, &QTipLabel::styleSheetParentDestroyed);
323 }
324 // QTBUG-64550: A font inherited by the style sheet might change the size,
325 // particular on Windows, where the tip is not parented on a window.
326 // The updatesSize() also makes sure that the content size be updated with
327 // correct content margin.
328 qTipLabel->updateSize(pos);
329 }
330#endif //QT_CONFIG(style_stylesheet)
331
332 QPoint p = pos;
333 const QScreen *screen = getTipScreen(pos, w);
334 // a QScreen's handle *should* never be null, so this is a bit paranoid
335 if (const QPlatformScreen *platformScreen = screen ? screen->handle() : nullptr) {
336 QPlatformCursor *cursor = platformScreen->cursor();
337 // default implementation of QPlatformCursor::size() returns QSize(16, 16)
338 const QSize nativeSize = cursor ? cursor->size() : QSize(16, 16);
339 const QSize cursorSize = QHighDpi::fromNativePixels(nativeSize,
340 platformScreen);
341 QPoint offset(2, cursorSize.height());
342 // assuming an arrow shape, we can just move to the side for very large cursors
343 if (cursorSize.height() > 2 * this->height())
344 offset = QPoint(cursorSize.width() / 2, 0);
345
346 p += offset;
347
348#if QT_CONFIG(wayland)
349 if (w) {
350 create();
351 if (auto waylandWindow = dynamic_cast<QNativeInterface::Private::QWaylandWindow*>(windowHandle()->handle())) {
352 QWidget *parentWindow = w->window();
353 parentWindow->createWinId();
354 windowHandle()->setTransientParent(parentWindow->windowHandle());
355
356 // based on the existing code below, by default position at 'p' stored at the bottom right of our rect
357 // then flip to the other arbitrary 4x24 space if constrained
358 const QRect controlGeometry = QRect(p.x() - 4, p.y() - 24, 4, 24)
359 .translated(-parentWindow->mapToGlobal(QPoint(0, 0)));
360 waylandWindow->setParentControlGeometry(controlGeometry);
361 waylandWindow->setExtendedWindowType(QNativeInterface::Private::QWaylandWindow::ToolTip);
362 }
363 }
364#endif
365
366 QRect screenRect = screen->availableGeometry();
367 if (p.x() + this->width() > screenRect.x() + screenRect.width())
368 p.rx() -= 4 + this->width();
369 if (p.y() + this->height() > screenRect.y() + screenRect.height())
370 p.ry() -= 24 + this->height();
371 if (p.y() < screenRect.y())
372 p.setY(screenRect.y());
373 if (p.x() + this->width() > screenRect.x() + screenRect.width())
374 p.setX(screenRect.x() + screenRect.width() - this->width());
375 if (p.x() < screenRect.x())
376 p.setX(screenRect.x());
377 if (p.y() + this->height() > screenRect.y() + screenRect.height())
378 p.setY(screenRect.y() + screenRect.height() - this->height());
379 }
380 this->move(p);
381}
382
383bool QTipLabel::tipChanged(const QPoint &pos, const QString &text, QObject *o)
384{
385 if (qTipLabel->text() != text)
386 return true;
387
388 if (o != widget)
389 return true;
390
391 if (!rect.isNull())
392 return !rect.contains(pos);
393 else
394 return false;
395}
396
397#if QT_CONFIG(style_stylesheet)
398/** \internal
399 Cleanup the _q_stylesheet_parent property.
400 */
401void QTipLabel::styleSheetParentDestroyed()
402{
403 setProperty("_q_stylesheet_parent", QVariant());
404 styleSheetParent = nullptr;
405}
406#endif
407
408/*!
409 Shows \a text as a tool tip, with the global position \a pos as
410 the point of interest. The tool tip will be shown with a platform
411 specific offset from this point of interest.
412
413 If you specify a non-empty rect the tip will be hidden as soon
414 as you move your cursor out of this area.
415
416 The \a rect is in the coordinates of the widget you specify with
417 \a w. If the \a rect is not empty you must specify a widget.
418 Otherwise this argument can be \nullptr but it is used to
419 determine the appropriate screen on multi-head systems.
420
421 The \a msecDisplayTime parameter specifies for how long the tool tip
422 will be displayed, in milliseconds. With the default value of -1, the
423 time is based on the length of the text.
424
425 If \a text is empty the tool tip is hidden. If the text is the
426 same as the currently shown tooltip, the tip will \e not move.
427 You can force moving by first hiding the tip with an empty text,
428 and then showing the new tip at the new position.
429*/
430
431void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect, int msecDisplayTime)
432{
433 showText(pos, text, w, rect, std::chrono::milliseconds(msecDisplayTime));
434}
435
436/*!
437 \overload
438 Shows \a text as a tool tip, with the global position \a pos as
439 the point of interest. The tool tip will be shown with a platform
440 specific offset from this point of interest.
441
442 If you specify a non-empty rect the tip will be hidden as soon
443 as you move your cursor out of this area.
444
445 The \a rect is in the coordinates of the widget you specify with
446 \a w. If the \a rect is not empty you must specify a widget.
447 Otherwise this argument can be \nullptr but it is used to
448 determine the appropriate screen on multi-head systems.
449
450 The \a displayTime parameter specifies for how long the tool tip
451 will be displayed in milliseconds. With the default value of -1, the
452 time is based on the length of the text.
453
454 If \a text is empty the tool tip is hidden. If the text is the
455 same as the currently shown tooltip, the tip will \e not move.
456 You can force moving by first hiding the tip with an empty text,
457 and then showing the new tip at the new position.
458
459 \since 6.13
460 */
461void QToolTip::showText(QPoint pos, const QString &text, QWidget *w, const QRect &rect,
462 std::chrono::milliseconds displayTime)
463{
464 if (qTipLabel && qTipLabel->isVisible()) { // a tip does already exist
465 if (text.isEmpty()){ // empty text means hide current tip
466 qTipLabel->hideTip();
467 return;
468 }
469 if (!qTipLabel->fadingOut) {
470 // If the tip has changed, reuse the one
471 // that is showing (removes flickering)
472 QPoint localPos = pos;
473 if (w)
474 localPos = w->mapFromGlobal(pos);
475 if (qTipLabel->tipChanged(localPos, text, w)) {
476 qTipLabel->reuseTip(text, displayTime, pos);
477 qTipLabel->setTipRect(w, rect);
478 qTipLabel->placeTip(pos, w);
479 }
480 return;
481 }
482 }
483
484 if (!text.isEmpty()) { // no tip can be reused, create new tip:
485 QWidget *tipLabelParent = [w]() -> QWidget* {
486#ifdef Q_OS_WIN32
487 // On windows, we can't use the widget as parent otherwise the window will be
488 // raised when the tooltip will be shown
489 Q_UNUSED(w);
490 return nullptr;
491#else
492 return w;
493#endif
494 }();
495 new QTipLabel(text, pos, tipLabelParent, displayTime); // sets qTipLabel to itself
496 QWidgetPrivate::get(qTipLabel)->setScreen(QTipLabel::getTipScreen(pos, w));
497 qTipLabel->setTipRect(w, rect);
498 qTipLabel->placeTip(pos, w);
499 qTipLabel->setObjectName("qtooltip_label"_L1);
500
501#if QT_CONFIG(effects)
502 if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip))
503 qFadeEffect(qTipLabel);
504 else if (QApplication::isEffectEnabled(Qt::UI_AnimateTooltip))
505 qScrollEffect(qTipLabel);
506 else
507 qTipLabel->showNormal();
508#else
509 qTipLabel->showNormal();
510#endif
511 }
512}
513
514/*!
515 \fn void QToolTip::hideText()
516 \since 4.2
517
518 Hides the tool tip. This is the same as calling showText() with an
519 empty string.
520
521 \sa showText()
522*/
523
524
525/*!
526 \since 4.4
527
528 Returns \c true if a tooltip is currently shown.
529
530 \sa showText()
531 */
532bool QToolTip::isVisible()
533{
534 return qTipLabel && qTipLabel->isVisible();
535}
536
537/*!
538 \since 4.4
539
540 Returns the tooltip text, if a tooltip is visible, or an
541 empty string if a tooltip is not visible.
542 */
543QString QToolTip::text()
544{
545 if (qTipLabel)
546 return qTipLabel->text();
547 return QString();
548}
549
550
551Q_GLOBAL_STATIC(QPalette, tooltip_palette)
552
553/*!
554 Returns the palette used to render tooltips.
555
556 \note Tool tips use the inactive color group of QPalette, because tool
557 tips are not active windows.
558*/
559QPalette QToolTip::palette()
560{
561 return *tooltip_palette();
562}
563
564/*!
565 \since 4.2
566
567 Returns the font used to render tooltips.
568*/
569QFont QToolTip::font()
570{
571 return QApplication::font("QTipLabel");
572}
573
574/*!
575 \since 4.2
576
577 Sets the \a palette used to render tooltips.
578
579 \note Tool tips use the inactive color group of QPalette, because tool
580 tips are not active windows.
581*/
582void QToolTip::setPalette(const QPalette &palette)
583{
584 *tooltip_palette() = palette;
585 if (qTipLabel)
586 qTipLabel->setPalette(palette);
587}
588
589/*!
590 \since 4.2
591
592 Sets the \a font used to render tooltips.
593*/
594void QToolTip::setFont(const QFont &font)
595{
596 QApplication::setFont(font, "QTipLabel");
597}
598
599QT_END_NAMESPACE
600
601#include "moc_qtooltip_p.cpp"
#define qApp
static QTipLabel * qTipLabel
Definition qtooltip.cpp:97