QtBase  v6.3.1
src_corelib_kernel_qobject.cpp
Go to the documentation of this file.
1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 ** * Redistributions of source code must retain the above copyright
25 ** notice, this list of conditions and the following disclaimer.
26 ** * Redistributions in binary form must reproduce the above copyright
27 ** notice, this list of conditions and the following disclaimer in
28 ** the documentation and/or other materials provided with the
29 ** distribution.
30 ** * Neither the name of The Qt Company Ltd nor the names of its
31 ** contributors may be used to endorse or promote products derived
32 ** from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50 
53 obj->metaObject()->className(); // returns "QPushButton"
54 
55 QPushButton::staticMetaObject.className(); // returns "QPushButton"
57 
58 
60 QPushButton::staticMetaObject.className(); // returns "QPushButton"
61 
62 QObject *obj = new QPushButton;
63 obj->metaObject()->className(); // returns "QPushButton"
65 
66 
68 QObject *obj = new QTimer; // QTimer inherits QObject
69 
70 QTimer *timer = qobject_cast<QTimer *>(obj);
71 // timer == (QObject *)obj
72 
73 QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
74 // button == nullptr
76 
77 
79 QTimer *timer = new QTimer; // QTimer inherits QObject
80 timer->inherits("QTimer"); // returns true
81 timer->inherits("QObject"); // returns true
82 timer->inherits("QAbstractButton"); // returns false
83 
84 // QVBoxLayout inherits QObject and QLayoutItem
86 layout->inherits("QObject"); // returns true
87 layout->inherits("QLayoutItem"); // returns true (even though QLayoutItem is not a QObject)
89 
90 
92 qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
93  qPrintable(objectName()), newPrecision);
95 
96 
98 class MainWindow : public QMainWindow
99 {
100 public:
102 
103 protected:
104  bool eventFilter(QObject *obj, QEvent *ev) override;
105 
106 private:
107  QTextEdit *textEdit;
108 };
109 
111 {
112  textEdit = new QTextEdit;
113  setCentralWidget(textEdit);
114 
115  textEdit->installEventFilter(this);
116 }
117 
119 {
120  if (obj == textEdit) {
121  if (event->type() == QEvent::KeyPress) {
122  QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
123  qDebug() << "Ate key press" << keyEvent->key();
124  return true;
125  } else {
126  return false;
127  }
128  } else {
129  // pass the event on to the parent class
131  }
132 }
134 
135 
139 
140 
142 class MyObject : public QObject
143 {
144  Q_OBJECT
145 
146 public:
147  MyObject(QObject *parent = nullptr);
148 
149 protected:
150  void timerEvent(QTimerEvent *event) override;
151 };
152 
154  : QObject(parent)
155 {
156  startTimer(50); // 50-millisecond timer
157  startTimer(1000); // 1-second timer
158  startTimer(60000); // 1-minute timer
159 
160  using namespace std::chrono;
161  startTimer(milliseconds(50));
162  startTimer(seconds(1));
163  startTimer(minutes(1));
164 
165  // since C++14 we can use std::chrono::duration literals, e.g.:
166  startTimer(100ms);
167  startTimer(5s);
168  startTimer(2min);
169  startTimer(1h);
170 }
171 
173 {
174  qDebug() << "Timer ID:" << event->timerId();
175 }
177 
178 
180 QList<QObject *> list = window()->queryList("QAbstractButton"));
181 foreach (QObject *obj, list)
182  static_cast<QAbstractButton *>(obj)->setEnabled(false);
184 
185 
187 QPushButton *button = parentWidget->findChild<QPushButton *>("button1");
189 
190 
192 QListWidget *list = parentWidget->findChild<QListWidget *>();
194 
195 
197 QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>("widgetname");
199 
200 
202 QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>();
204 
205 
207 monitoredObj->installEventFilter(filterObj);
209 
210 
212 class KeyPressEater : public QObject
213 {
214  Q_OBJECT
215  ...
216 
217 protected:
218  bool eventFilter(QObject *obj, QEvent *event) override;
219 };
220 
222 {
223  if (event->type() == QEvent::KeyPress) {
224  QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
225  qDebug("Ate key press %d", keyEvent->key());
226  return true;
227  } else {
228  // standard event processing
229  return QObject::eventFilter(obj, event);
230  }
231 }
233 
234 
239 
240 pushButton->installEventFilter(keyPressEater);
241 listView->installEventFilter(keyPressEater);
243 
244 
246 MyWindow::MyWindow()
247 {
248  QLabel *senderLabel = new QLabel(tr("Name:"));
249  QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
251 }
252 
253 
255 int n = messages.count();
256 showMessage(tr("%n message(s) saved", "", n));
258 
259 
261 n == 1 ? tr("%n message saved") : tr("%n messages saved")
263 
264 
266 label->setText(tr("F\374r \310lise"));
268 
269 
271 if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
273  get_the_value(&data); // expensive operation
274  emit valueChanged(data);
275 }
277 
278 
280 QLabel *label = new QLabel;
282 QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
283  label, SLOT(setNum(int)));
285 
286 
288 // WRONG
289 QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
290  label, SLOT(setNum(int value)));
292 
293 
295 class MyWidget : public QWidget
296 {
297  Q_OBJECT
298 
299 public:
300  MyWidget();
301 
302 signals:
304 
305 private:
306  QPushButton *myButton;
307 };
308 
310 {
311  myButton = new QPushButton(this);
312  connect(myButton, SIGNAL(clicked()),
313  this, SIGNAL(buttonClicked()));
314 }
316 
317 
320 (Make sure 'MyType' is registered using qRegisterMetaType().)
322 
323 
324 disconnect(myObject, nullptr, nullptr, nullptr);
327 
328 
332 
333 
335 disconnect(myObject, SIGNAL(mySignal()), nullptr, nullptr);
337 
338 
340 myObject->disconnect(SIGNAL(mySignal()));
342 
343 
345 disconnect(myObject, nullptr, myReceiver, nullptr);
347 
348 
350 myObject->disconnect(myReceiver);
352 
353 
355 if (signal == QMetaMethod::fromSignal(&MyObject::valueChanged)) {
356  // signal is valueChanged
357 }
359 
360 
362 void on_<object name>_<signal name>(<signal parameters>);
364 
365 
369 
370 
372 class MyClass : public QObject
373 {
374  Q_OBJECT
375  Q_CLASSINFO("Author", "Pierre Gendron")
376  Q_CLASSINFO("URL", "http://www.my-organization.qc.ca")
377 
378 public:
379  ...
380 };
382 
384 Q_PROPERTY(QString title READ title WRITE setTitle USER true)
386 
387 
389 class MyClass : public QObject
390 {
391  Q_OBJECT
392 
393 public:
394  MyClass(QObject *parent = nullptr);
396 
397  enum Priority { High, Low, VeryHigh, VeryLow };
398  Q_ENUM(Priority)
400  Priority priority() const;
401 };
403 
404 
407 {
408  Q_OBJECT
409 
410 public:
411  ...
413  NoUpdate = 0x0000,
414  Clear = 0x0001,
415  Select = 0x0002,
416  Deselect = 0x0004,
417  Toggle = 0x0008,
418  Current = 0x0010,
419  Rows = 0x0020,
420  Columns = 0x0040,
424  };
425 
426  Q_DECLARE_FLAGS(SelectionFlags, SelectionFlag)
427  Q_FLAG(SelectionFlags)
428  ...
429 }
431 
432 
434 //: This name refers to a host name.
435 hostNameLabel->setText(tr("Name:"));
436 
437 /*: This text refers to a C++ code example. */
438 QString example = tr("Example");
440 
442 QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildrenOnly);
444 
445 
447 QListWidget *list = parentWidget->findChild<QListWidget *>(QString(), Qt::FindDirectChildrenOnly);
449 
450 
454 
456 QLabel *label = new QLabel;
461 
463 void someFunction();
467 
471 socket->connectToHost("qt-project.org", 80);
473  socket->write("GET " + page + "\r\n");
474  });
476 
478 disconnect(myObject, &MyObject::mySignal(), nullptr, nullptr);
480 
485 
487 static const QMetaMethod valueChangedSignal = QMetaMethod::fromSignal(&MyObject::valueChanged);
488 if (isSignalConnected(valueChangedSignal)) {
490  data = get_the_value(); // expensive operation
491  emit valueChanged(data);
492 }
494 
496 void someFunction();
500 
502 QByteArray page = ...;
504 socket->connectToHost("qt-project.org", 80);
506  socket->write("GET " + page + "\r\n");
507  }, Qt::AutoConnection);
509 
511 class MyClass : public QWidget
512 {
513  Q_OBJECT
514 
515 public:
516  MyClass(QWidget *parent = nullptr);
518 
519  bool event(QEvent* ev) override
520  {
521  if (ev->type() == QEvent::PolishRequest) {
522  // overwrite handling of PolishRequest if any
523  doThings();
524  return true;
525  } else if (ev->type() == QEvent::Show) {
526  // complement handling of Show if any
527  doThings2();
528  QWidget::event(ev);
529  return true;
530  }
531  // Make sure the rest of events are handled
532  return QWidget::event(ev);
533  }
534 };
536 
538 //: This is a comment for the translator.
539 //= qtn_foo_bar
540 //~ loc-layout_id foo_dialog
541 //~ loc-blank False
542 //~ magic-stuff This might mean something magic.
543 QString text = MyMagicClass::tr("Sim sala bim.");
545 
547 QString text = QScrollBar::tr("Page up");
549 
551 {
552 const QSignalBlocker blocker(someQObject);
553 // no signals here
554 }
556 
558 const bool wasBlocked = someQObject->blockSignals(true);
559 // no signals here
560 someQObject->blockSignals(wasBlocked);
bool eventFilter(QObject *obj, QEvent *event) override
bool event(QEvent *event) override
bool eventFilter(QObject *obj, QEvent *ev) override
MyClass(QObject *parent=nullptr)
MyClass(QWidget *parent=nullptr)
bool event(QEvent *ev) override
[0]
Definition: myobject.h:58
MyObject()
[0]
Definition: myobject.cpp:57
void timerEvent(QTimerEvent *event) override
void buttonClicked()
The QAbstractButton class is the abstract base class of button widgets, providing functionality commo...
void clicked(bool checked=false)
virtual void connectToHost(const QString &hostName, quint16 port, OpenMode mode=ReadWrite, NetworkLayerProtocol protocol=AnyIPProtocol)
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:85
static QCoreApplication * instance()
The QEvent class is the base class of all event classes. Event objects contain event parameters.
Definition: qcoreevent.h:58
@ PolishRequest
Definition: qcoreevent.h:123
@ KeyPress
Definition: qcoreevent.h:77
@ Show
Definition: qcoreevent.h:89
Type type() const
Definition: qcoreevent.h:307
qint64 write(const char *data, qint64 len)
Definition: qiodevice.cpp:1681
The QKeyEvent class describes a key event.
Definition: qevent.h:471
int key() const
Definition: qevent.h:484
void setText(const QString &)
Definition: qlabel.cpp:297
The QLineEdit widget is a one-line text editor.
Definition: qlineedit.h:64
void textChanged(const QString &)
The QListView class provides a list or icon view onto a model.
Definition: qlistview.h:53
The QListWidget class provides an item-based list widget.
Definition: qlistwidget.h:188
The QMainWindow class provides a main application window.\inmodule QtWidgets.
Definition: qmainwindow.h:61
void setCentralWidget(QWidget *widget)
The QMetaMethod class provides meta-data about a member function.
Definition: qmetaobject.h:54
static QMetaMethod fromSignal(PointerToMemberFunction signal)
Definition: qmetaobject.h:175
The QObject class is the base class of all Qt objects.
Definition: qobject.h:125
int startTimer(int interval, Qt::TimerType timerType=Qt::CoarseTimer)
Definition: qobject.cpp:1765
Q_INVOKABLE QObject(QObject *parent=nullptr)
Definition: qobject.cpp:913
T findChild(const QString &aName=QString(), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
Definition: qobject.h:168
bool isSignalConnected(const QMetaMethod &signal) const
Definition: qobject.cpp:2613
QObject * parent() const
Definition: qobject.h:409
void moveToThread(QThread *thread)
Definition: qobject.cpp:1572
static QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Definition: qobject.cpp:2772
virtual bool event(QEvent *event)
Definition: qobject.cpp:1329
virtual bool eventFilter(QObject *watched, QEvent *event)
Definition: qobject.cpp:1484
static bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
Definition: qobject.cpp:3048
friend class QWidget
Definition: qobject.h:445
int receivers(const char *signal) const
Definition: qobject.cpp:2554
bool inherits(const char *classname) const
Definition: qobject.h:411
The QScrollBar widget provides a vertical or horizontal scroll bar.
Definition: qscrollbar.h:56
Exception-safe wrapper around QObject::blockSignals().
Definition: qobject.h:527
The QString class provides a Unicode character string.
Definition: qstring.h:388
The QTcpSocket class provides a TCP socket.
Definition: qtcpsocket.h:54
The QTextEdit class provides a widget that is used to edit and display both plain and rich text.
Definition: qtextedit.h:63
The QTimerEvent class contains parameters that describe a timer event.
Definition: qcoreevent.h:367
The QTimer class provides repetitive and single-shot timers.
Definition: qtimer.h:58
The QVBoxLayout class lines up widgets vertically.
Definition: qboxlayout.h:127
bool event(QEvent *event) override
Definition: qwidget.cpp:8772
QPushButton
[1]
QQueue< int > queue
[0]
myinstance setPriority(MyClass::VeryHigh)
auto signal
QList< QVariant > arguments
#define true
Definition: ftrandom.c:51
auto it unsigned count const
Definition: hb-iter.hh:848
std::chrono::milliseconds ms
@ FindDirectChildrenOnly
Definition: qnamespace.h:1479
@ AutoConnection
Definition: qnamespace.h:1305
@ QueuedConnection
Definition: qnamespace.h:1307
#define QString()
Definition: parse-defines.h:51
void
Definition: png.h:1080
EGLOutputLayerEXT EGLint EGLAttrib value
#define Q_DECLARE_FLAGS(Flags, Enum)
Definition: qflags.h:210
@ text
int qRegisterMetaType(const char *typeName)
Definition: qmetatype.h:1291
#define SLOT(a)
Definition: qobjectdefs.h:87
#define SIGNAL(a)
Definition: qobjectdefs.h:88
GLenum type
Definition: qopengl.h:270
GLuint GLsizei const GLchar * label
[43]
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
GLfloat n
GLfloat GLfloat GLfloat GLfloat h
struct _cl_event * event
Definition: qopenglext.h:2998
GLhandleARB obj
[2]
Definition: qopenglext.h:4164
GLdouble s
[6]
Definition: qopenglext.h:235
#define tr(X)
#define Q_ENUM(x)
Definition: qtmetamacros.h:104
#define Q_PROPERTY(...)
Definition: qtmetamacros.h:92
#define Q_OBJECT
Definition: qtmetamacros.h:158
#define Q_CLASSINFO(name, value)
Definition: qtmetamacros.h:88
#define Q_FLAG(x)
Definition: qtmetamacros.h:105
#define signals
Definition: qtmetamacros.h:77
#define emit
Definition: qtmetamacros.h:85
QPushButton * pushButton
QList< QPushButton * > childButtons
[42]
const bool wasBlocked
[explicit tr context]
QAbstractButton * button
[9]
void on_button1_clicked()
[33]
QList< QWidget * > widgets
[11]
showMessage(tr("%n message(s) saved", "", n))
QObject * obj
[1]
QVBoxLayout * layout
QLineEdit * lineEdit
MyClass setText
QListView * listView
QString title
[35]
QList< QObject * > list
[8]
QScrollBar * scrollBar
KeyPressEater * keyPressEater
[15]
QByteArray page
[45]
QTcpSocket * socket
[1]
QList< QPushButton * > allPButtons
[12]
qDebug("MyClass::setPrecision(): (%s) invalid precision %f", qPrintable(objectName()), newPrecision)
[4]
if(receivers(SIGNAL(valueChanged(QByteArray))) > 0)
[20]
QTimer * timer
[3]
void on_< object name > _< signal name >(< signal parameters >)
[32]
aWidget window() -> setWindowTitle("New Window Title")
[2]
g setTitle("&User information")
[0]
constexpr const auto messages
IUIAutomationTreeWalker __RPC__deref_out_opt IUIAutomationElement ** parent