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
qwhatsthis.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 "qwhatsthis.h"
6#include "qpointer.h"
7#include "qapplication.h"
8#include <private/qguiapplication_p.h>
9#include "qwidget.h"
10#include "qevent.h"
11#include "qpixmap.h"
12#include "qscreen.h"
13#include "qpainter.h"
14#if QT_CONFIG(action)
15#include "qaction.h"
16#endif // QT_CONFIG(action)
17#include "qcursor.h"
18#include "qbitmap.h"
19#include "qtextdocument.h"
20#include <qpa/qplatformtheme.h>
21#include "private/qtextdocumentlayout_p.h"
22#include "qdebug.h"
23#if QT_CONFIG(accessibility)
24#include "qaccessible.h"
25#endif
26
28
29/*!
30 \class QWhatsThis
31 \brief The QWhatsThis class provides a simple description of any
32 widget, i.e. answering the question "What's This?".
33
34 \ingroup helpsystem
35 \inmodule QtWidgets
36
37 "What's This?" help is part of an application's online help
38 system, and provides users with information about the
39 functionality and usage of a particular widget. "What's This?"
40 help texts are typically longer and more detailed than
41 \l{QToolTip}{tooltips}, but generally provide less information
42 than that supplied by separate help windows.
43
44 QWhatsThis provides a single window with an explanatory text that
45 pops up when the user asks "What's This?". The default way for
46 users to ask the question is to move the focus to the relevant
47 widget and press Shift+F1. The help text appears immediately; it
48 goes away as soon as the user does something else.
49 (Note that if there is a shortcut for Shift+F1, this mechanism
50 will not work.) Some dialogs provide a "?" button that users can
51 click to enter "What's This?" mode; they then click the relevant
52 widget to pop up the "What's This?" window. It is also possible to
53 provide a a menu option or toolbar button to switch into "What's
54 This?" mode.
55
56 To add "What's This?" text to a widget or an action, you simply
57 call QWidget::setWhatsThis() or QAction::setWhatsThis().
58
59 The text can be either rich text or plain text. If you specify a
60 rich text formatted string, it will be rendered using the default
61 stylesheet, making it possible to embed images in the displayed
62 text. To be as fast as possible, the default stylesheet uses a
63 simple method to determine whether the text can be rendered as
64 plain text. See Qt::mightBeRichText() for details.
65
66 \snippet whatsthis/whatsthis.cpp 0
67
68 An alternative way to enter "What's This?" mode is to call
69 createAction(), and add the returned QAction to either a menu or
70 a tool bar. By invoking this context help action (in the picture
71 below, the button with the arrow and question mark icon) the user
72 switches into "What's This?" mode. If they now click on a widget
73 the appropriate help text is shown. The mode is left when help is
74 given or when the user presses Esc.
75
76 \image whatsthis.png {"What's This?" mode for New File button}
77
78 You can enter "What's This?" mode programmatically with
79 enterWhatsThisMode(), check the mode with inWhatsThisMode(), and
80 return to normal mode with leaveWhatsThisMode().
81
82 If you want to control the "What's This?" behavior of a widget
83 manually see Qt::WA_CustomWhatsThis.
84
85 It is also possible to show different help texts for different
86 regions of a widget, by using a QHelpEvent of type
87 QEvent::WhatsThis. Intercept the help event in your widget's
88 QWidget::event() function and call QWhatsThis::showText() with the
89 text you want to display for the position specified in
90 QHelpEvent::pos(). If the text is rich text and the user clicks
91 on a link, the widget also receives a QWhatsThisClickedEvent with
92 the link's reference as QWhatsThisClickedEvent::href(). If a
93 QWhatsThisClickedEvent is handled (i.e. QWidget::event() returns
94 true), the help window remains visible. Call
95 QWhatsThis::hideText() to hide it explicitly.
96
97 \sa QToolTip
98*/
99
100class QWhatsThat : public QWidget
101{
103
104public:
107
109
110protected:
111 void mousePressEvent(QMouseEvent*) override;
112 void mouseReleaseEvent(QMouseEvent*) override;
113 void mouseMoveEvent(QMouseEvent*) override;
114 void keyPressEvent(QKeyEvent*) override;
115 void paintEvent(QPaintEvent*) override;
116
117private:
118 QPointer<QWidget>widget;
119 bool pressed;
120 QString text;
121 QTextDocument* doc;
122 QString anchor;
123};
124
125QWhatsThat *QWhatsThat::instance = nullptr;
126
127// shadowWidth not const, for XP drop-shadow-fu turns it to 0
128static int shadowWidth = 6; // also used as '5' and '6' and even '8' below
129static constexpr int vMargin = 8;
130static constexpr int hMargin = 12;
131
132static inline bool dropShadow()
133{
134 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
135 return theme->themeHint(QPlatformTheme::DropShadow).toBool();
136 return false;
137}
138
139QWhatsThat::QWhatsThat(const QString &txt, QWidget *parent, QWidget *showTextFor, QSize screenSize)
140 : QWidget(parent, Qt::Popup),
141 widget(showTextFor), pressed(false), text(txt)
142{
143 delete instance;
144 instance = this;
145 setAttribute(Qt::WA_DeleteOnClose, true);
146 setAttribute(Qt::WA_NoSystemBackground, true);
147 if (parent)
148 setPalette(parent->palette());
149 setMouseTracking(true);
150 setFocusPolicy(Qt::StrongFocus);
151#ifndef QT_NO_CURSOR
152 setCursor(Qt::ArrowCursor);
153#endif
154 QRect r;
155 doc = nullptr;
156 ensurePolished(); // Ensures style sheet font before size calc
157 if (Qt::mightBeRichText(text)) {
158 doc = new QTextDocument();
159 doc->setUndoRedoEnabled(false);
160 doc->setDefaultFont(QApplication::font(this));
161#ifdef QT_NO_TEXTHTMLPARSER
162 doc->setPlainText(text);
163#else
164 doc->setHtml(text);
165#endif
166 doc->setUndoRedoEnabled(false);
167 doc->adjustSize();
168 r.setTop(0);
169 r.setLeft(0);
170 r.setSize(doc->size().toSize());
171 }
172 else
173 {
174 int sw = QGuiApplication::primaryScreen()->virtualGeometry().width() / 3;
175 if (sw < 200)
176 sw = 200;
177 else if (sw > 300)
178 sw = 300;
179
180 r = fontMetrics().boundingRect(0, 0, sw, 1000,
181 Qt::AlignLeft | Qt::AlignTop
182 | Qt::TextWordWrap | Qt::TextExpandTabs,
183 text);
184 }
185 shadowWidth = dropShadow() ? 0 : 6;
186 const QSize sz(r.width() + 2 * hMargin + shadowWidth, r.height() + 2 * vMargin + shadowWidth);
187 resize(sz.boundedTo(screenSize));
188}
189
191{
192 instance = nullptr;
193 if (doc)
194 delete doc;
195}
196
197void QWhatsThat::mousePressEvent(QMouseEvent* e)
198{
199 pressed = true;
200 if (e->button() == Qt::LeftButton && rect().contains(e->position().toPoint())) {
201 if (doc)
202 anchor = doc->documentLayout()->anchorAt(e->position() - QPointF(hMargin, vMargin));
203 return;
204 }
205 close();
206}
207
208void QWhatsThat::mouseReleaseEvent(QMouseEvent* e)
209{
210 if (!pressed)
211 return;
212 if (widget && e->button() == Qt::LeftButton && doc && rect().contains(e->position().toPoint())) {
213 QString a = doc->documentLayout()->anchorAt(e->position() - QPointF(hMargin, vMargin));
214 QString href;
215 if (anchor == a)
216 href = a;
217 anchor.clear();
218 if (!href.isEmpty()) {
219 QWhatsThisClickedEvent e(href);
220 if (QCoreApplication::sendEvent(widget, &e))
221 return;
222 }
223 }
224 close();
225}
226
227void QWhatsThat::mouseMoveEvent(QMouseEvent* e)
228{
229#ifdef QT_NO_CURSOR
230 Q_UNUSED(e);
231#else
232 if (!doc)
233 return;
234 QString a = doc->documentLayout()->anchorAt(e->position() - QPointF(hMargin, vMargin));
235 if (!a.isEmpty())
236 setCursor(Qt::PointingHandCursor);
237 else
238 setCursor(Qt::ArrowCursor);
239#endif
240}
241
242void QWhatsThat::keyPressEvent(QKeyEvent*)
243{
244 close();
245}
246
247void QWhatsThat::paintEvent(QPaintEvent*)
248{
249 const bool drawShadow = dropShadow();
250
251 QRect r = rect();
252 r.adjust(0, 0, -1, -1);
253 if (drawShadow)
254 r.adjust(0, 0, -shadowWidth, -shadowWidth);
255 QPainter p(this);
256 p.setPen(QPen(palette().toolTipText(), 0));
257 p.setBrush(palette().toolTipBase());
258 p.drawRect(r);
259 int w = r.width();
260 int h = r.height();
261 p.setPen(palette().brush(QPalette::Dark).color());
262 p.drawRect(1, 1, w-2, h-2);
263 if (drawShadow) {
264 p.setPen(palette().shadow().color());
265 p.drawPoint(w + 5, 6);
266 p.drawLine(w + 3, 6, w + 5, 8);
267 p.drawLine(w + 1, 6, w + 5, 10);
268 int i;
269 for(i=7; i < h; i += 2)
270 p.drawLine(w, i, w + 5, i + 5);
271 for(i = w - i + h; i > 6; i -= 2)
272 p.drawLine(i, h, i + 5, h + 5);
273 for(; i > 0 ; i -= 2)
274 p.drawLine(6, h + 6 - i, i + 5, h + 5);
275 }
276 r.adjust(0, 0, 1, 1);
277 p.setPen(palette().toolTipText().color());
278 r.adjust(hMargin, vMargin, -hMargin, -vMargin);
279
280 if (doc) {
281 p.translate(r.x(), r.y());
282 QRect rect = r;
283 rect.translate(-r.x(), -r.y());
284 p.setClipRect(rect);
285 QAbstractTextDocumentLayout::PaintContext context;
286 context.palette.setBrush(QPalette::Text, context.palette.toolTipText());
287 doc->documentLayout()->draw(&p, context);
288 }
289 else
290 {
291 p.drawText(r, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap | Qt::TextExpandTabs, text);
292 }
293}
294
295#if QT_CONFIG(imageformat_xpm)
296static const char * const button_image[] = {
297"16 16 3 1",
298" c None",
299"o c #000000",
300"a c #000080",
301"o aaaaa ",
302"oo aaa aaa ",
303"ooo aaa aaa",
304"oooo aa aa",
305"ooooo aa aa",
306"oooooo a aaa",
307"ooooooo aaa ",
308"oooooooo aaa ",
309"ooooooooo aaa ",
310"ooooo aaa ",
311"oo ooo ",
312"o ooo aaa ",
313" ooo aaa ",
314" ooo ",
315" ooo ",
316" ooo "};
317#endif
318
320{
321 public:
325 bool eventFilter(QObject *, QEvent *) override;
326#if QT_CONFIG(action)
328#endif // QT_CONFIG(action)
329 static void say(QWidget *, const QString &, int x = 0, int y = 0);
330 static void notifyToplevels(QEvent *e);
332};
333
334void QWhatsThisPrivate::notifyToplevels(QEvent *e)
335{
336 const QWidgetList toplevels = QApplication::topLevelWidgets();
337 for (auto *w : toplevels)
338 QCoreApplication::sendEvent(w, e);
339}
340
342
344 : leaveOnMouseRelease(false)
345{
346 instance = this;
347 qApp->installEventFilter(this);
348
349 QPoint pos = QCursor::pos();
350 if (QWidget *w = QApplication::widgetAt(pos)) {
351 QHelpEvent e(QEvent::QueryWhatsThis, w->mapFromGlobal(pos), pos);
352 const bool sentEvent = QCoreApplication::sendEvent(w, &e);
353#ifdef QT_NO_CURSOR
354 Q_UNUSED(sentEvent);
355#else
356 QGuiApplication::setOverrideCursor((!sentEvent || !e.isAccepted())?
357 Qt::ForbiddenCursor:Qt::WhatsThisCursor);
358 } else {
359 QGuiApplication::setOverrideCursor(Qt::WhatsThisCursor);
360#endif
361 }
362#if QT_CONFIG(accessibility)
363 QAccessibleEvent event(this, QAccessible::ContextHelpStart);
364 QAccessible::updateAccessibility(&event);
365#endif
366}
367
369{
370#if QT_CONFIG(action)
371 if (action)
372 action->setChecked(false);
373#endif // QT_CONFIG(action)
374#ifndef QT_NO_CURSOR
375 QGuiApplication::restoreOverrideCursor();
376#endif
377#if QT_CONFIG(accessibility)
378 QAccessibleEvent event(this, QAccessible::ContextHelpEnd);
379 QAccessible::updateAccessibility(&event);
380#endif
381 instance = nullptr;
382}
383
384bool QWhatsThisPrivate::eventFilter(QObject *o, QEvent *e)
385{
386 if (!o->isWidgetType())
387 return false;
388 QWidget * w = static_cast<QWidget *>(o);
389 bool customWhatsThis = w->testAttribute(Qt::WA_CustomWhatsThis);
390 switch (e->type()) {
391 case QEvent::MouseButtonPress:
392 {
393 QMouseEvent *me = static_cast<QMouseEvent*>(e);
394 if (me->button() == Qt::RightButton || customWhatsThis)
395 return false;
396 QHelpEvent e(QEvent::WhatsThis, me->position().toPoint(), me->globalPosition().toPoint());
397 if (!QCoreApplication::sendEvent(w, &e) || !e.isAccepted())
398 leaveOnMouseRelease = true;
399
400 } break;
401
402 case QEvent::MouseMove:
403 {
404 QMouseEvent *me = static_cast<QMouseEvent*>(e);
405 QHelpEvent e(QEvent::QueryWhatsThis, me->position().toPoint(), me->globalPosition().toPoint());
406 const bool sentEvent = QCoreApplication::sendEvent(w, &e);
407#ifdef QT_NO_CURSOR
408 Q_UNUSED(sentEvent);
409#else
410 QGuiApplication::changeOverrideCursor((!sentEvent || !e.isAccepted())?
411 Qt::ForbiddenCursor:Qt::WhatsThisCursor);
412#endif
413 Q_FALLTHROUGH();
414 }
415 case QEvent::MouseButtonRelease:
416 case QEvent::MouseButtonDblClick:
417 if (leaveOnMouseRelease && e->type() == QEvent::MouseButtonRelease)
418 QWhatsThis::leaveWhatsThisMode();
419 if (static_cast<QMouseEvent*>(e)->button() == Qt::RightButton || customWhatsThis)
420 return false; // ignore RMB release
421 break;
422 case QEvent::KeyPress:
423 {
424 QKeyEvent *kev = static_cast<QKeyEvent *>(e);
425#if QT_CONFIG(shortcut)
426 if (kev->matches(QKeySequence::Cancel)) {
427 QWhatsThis::leaveWhatsThisMode();
428 return true;
429 } else
430#endif
431 if (customWhatsThis) {
432 return false;
433 } else if (kev->key() == Qt::Key_Menu ||
434 (kev->key() == Qt::Key_F10 &&
435 kev->modifiers() == Qt::ShiftModifier)) {
436 // we don't react to these keys, they are used for context menus
437 return false;
438 } else if (kev->key() != Qt::Key_Shift && kev->key() != Qt::Key_Alt // not a modifier key
439 && kev->key() != Qt::Key_Control && kev->key() != Qt::Key_Meta) {
440 QWhatsThis::leaveWhatsThisMode();
441 }
442 } break;
443 default:
444 return false;
445 }
446 return true;
447}
448
449#if QT_CONFIG(action)
450class QWhatsThisAction: public QAction
451{
452 Q_OBJECT
453
454public:
455 explicit QWhatsThisAction(QObject* parent = nullptr);
456
457private slots:
458 void actionTriggered();
459};
460
461QWhatsThisAction::QWhatsThisAction(QObject *parent) : QAction(tr("What's This?"), parent)
462{
463#if QT_CONFIG(imageformat_xpm)
464 QPixmap p(button_image);
465 setIcon(p);
466#endif
467 setCheckable(true);
468 connect(this, &QWhatsThisAction::triggered, this, &QWhatsThisAction::actionTriggered);
469#ifndef QT_NO_SHORTCUT
470 setShortcut(Qt::ShiftModifier | Qt::Key_F1);
471#endif
472}
473
474void QWhatsThisAction::actionTriggered()
475{
476 if (isChecked()) {
477 QWhatsThis::enterWhatsThisMode();
478 QWhatsThisPrivate::instance->action = this;
479 }
480}
481#endif // QT_CONFIG(action)
482
483/*!
484 This function switches the user interface into "What's This?"
485 mode. The user interface can be switched back into normal mode by
486 the user (e.g. by them clicking or pressing Esc), or
487 programmatically by calling leaveWhatsThisMode().
488
489 When entering "What's This?" mode, a QEvent of type
490 Qt::EnterWhatsThisMode is sent to all toplevel widgets.
491
492 \sa inWhatsThisMode(), leaveWhatsThisMode()
493*/
494void QWhatsThis::enterWhatsThisMode()
495{
496 if (QWhatsThisPrivate::instance)
497 return;
498 (void) new QWhatsThisPrivate;
499 QEvent e(QEvent::EnterWhatsThisMode);
500 QWhatsThisPrivate::notifyToplevels(&e);
501 }
502
503/*!
504 Returns \c true if the user interface is in "What's This?" mode;
505 otherwise returns \c false.
506
507 \sa enterWhatsThisMode()
508*/
509bool QWhatsThis::inWhatsThisMode()
510{
511 return (QWhatsThisPrivate::instance != nullptr);
512}
513
514/*!
515 If the user interface is in "What's This?" mode, this function
516 switches back to normal mode; otherwise it does nothing.
517
518 When leaving "What's This?" mode, a QEvent of type
519 Qt::LeaveWhatsThisMode is sent to all toplevel widgets.
520
521 \sa enterWhatsThisMode(), inWhatsThisMode()
522*/
523void QWhatsThis::leaveWhatsThisMode()
524{
525 delete QWhatsThisPrivate::instance;
526 QEvent e(QEvent::LeaveWhatsThisMode);
527 QWhatsThisPrivate::notifyToplevels(&e);
528}
529
530void QWhatsThisPrivate::say(QWidget * widget, const QString &text, int x, int y)
531{
532 if (text.size() == 0)
533 return;
534 // okay, now to find a suitable location
535 QScreen *screen = widget ? widget->screen()
536 : QGuiApplication::screenAt(QPoint(x, y));
537 if (!screen)
538 screen = QGuiApplication::primaryScreen();
539 QRect screenRect = screen->geometry();
540
541 // make a fresh widget, and set it up
542 QWhatsThat *whatsThat = new QWhatsThat(text, nullptr, widget, screenRect.size());
543
544 int w = whatsThat->width();
545 int h = whatsThat->height();
546 int sx = screenRect.x();
547 int sy = screenRect.y();
548
549 // first try locating the widget immediately above/below,
550 // with nice alignment if possible.
551 QPoint pos;
552 if (widget)
553 pos = widget->mapToGlobal(QPoint(0,0));
554
555 if (widget && w > widget->width() + 16)
556 x = pos.x() + widget->width()/2 - w/2;
557 else
558 x = x - w/2;
559
560 // squeeze it in if that would result in part of what's this
561 // being only partially visible
562 if (x + w + shadowWidth > screenRect.right()) {
563 x = widget ? qMin(screenRect.right(), pos.x() + widget->width()) : screenRect.right();
564 x -=w;
565 }
566
567 if (x < sx)
568 x = sx;
569
570 if (widget && h > widget->height() + 16) {
571 y = pos.y() + widget->height() + 2; // below, two pixels spacing
572 // what's this is above or below, wherever there's most space
573 if (y + h + 10 > screenRect.bottom())
574 y = pos.y() + 2 - shadowWidth - h; // above, overlap
575 }
576 y = y + 2;
577
578 // squeeze it in if that would result in part of what's this
579 // being only partially visible
580 if (y + h + shadowWidth > screenRect.bottom()) {
581 y = widget ? qMin(screenRect.bottom(), pos.y() + widget->height()) : screenRect.bottom();
582 y -= h;
583 }
584 if (y < sy)
585 y = sy;
586
587 whatsThat->move(x, y);
588 whatsThat->show();
589 whatsThat->grabKeyboard();
590}
591
592/*!
593 Shows \a text as a "What's This?" window, at global position \a
594 pos. The optional widget argument, \a w, is used to determine the
595 appropriate screen on multi-head systems.
596
597 \sa hideText()
598*/
599void QWhatsThis::showText(const QPoint &pos, const QString &text, QWidget *w)
600{
601 leaveWhatsThisMode();
602 QWhatsThisPrivate::say(w, text, pos.x(), pos.y());
603}
604
605/*!
606 If a "What's This?" window is showing, this destroys it.
607
608 \sa showText()
609*/
610void QWhatsThis::hideText()
611{
612 delete QWhatsThat::instance;
613}
614
615/*!
616 Returns a ready-made QAction, used to invoke "What's This?" context
617 help, with the given \a parent.
618
619 The returned QAction provides a convenient way to let users enter
620 "What's This?" mode.
621*/
622#if QT_CONFIG(action)
623QAction *QWhatsThis::createAction(QObject *parent)
624{
625 return new QWhatsThisAction(parent);
626}
627#endif // QT_CONFIG(action)
628
629QT_END_NAMESPACE
630
631#include "qwhatsthis.moc"
The QHelpEvent class provides an event that is used to request helpful information about a particular...
Definition qevent.h:810
friend class QPainter
friend class QWidget
Definition qpainter.h:432
\inmodule QtCore\reentrant
Definition qpoint.h:30
void keyPressEvent(QKeyEvent *) override
This event handler, for event event, can be reimplemented in a subclass to receive key press events f...
void mouseReleaseEvent(QMouseEvent *) override
This event handler, for event event, can be reimplemented in a subclass to receive mouse release even...
void mouseMoveEvent(QMouseEvent *) override
This event handler, for event event, can be reimplemented in a subclass to receive mouse move events ...
void mousePressEvent(QMouseEvent *) override
This event handler, for event event, can be reimplemented in a subclass to receive mouse press events...
void paintEvent(QPaintEvent *) override
This event handler can be reimplemented in a subclass to receive paint events passed in event.
static QWhatsThat * instance
static void say(QWidget *, const QString &, int x=0, int y=0)
static QWhatsThisPrivate * instance
static void notifyToplevels(QEvent *e)
bool eventFilter(QObject *, QEvent *) override
Filters events if this object has been installed as an event filter for the watched object.
Combined button and popup list for selecting options.
Definition qcompare.h:111
Q_GUI_EXPORT bool mightBeRichText(QAnyStringView)
Returns true if the string text is likely to be rich text; otherwise returns false.
#define qApp
static constexpr int hMargin
static constexpr int vMargin
static int shadowWidth
static bool dropShadow()