Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
src_corelib_kernel_qobject.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
6obj->metaObject()->className(); // returns "QPushButton"
7
8QPushButton::staticMetaObject.className(); // returns "QPushButton"
10
11
13QPushButton::staticMetaObject.className(); // returns "QPushButton"
14
16obj->metaObject()->className(); // returns "QPushButton"
18
19
21QObject *obj = new QTimer; // QTimer inherits QObject
22
23QTimer *timer = qobject_cast<QTimer *>(obj);
24// timer == (QObject *)obj
25
26QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
27// button == nullptr
29
30
32QTimer *timer = new QTimer; // QTimer inherits QObject
33timer->inherits("QTimer"); // returns true
34timer->inherits("QObject"); // returns true
35timer->inherits("QAbstractButton"); // returns false
36
37// QVBoxLayout inherits QObject and QLayoutItem
39layout->inherits("QObject"); // returns true
40layout->inherits("QLayoutItem"); // returns true (even though QLayoutItem is not a QObject)
42
43
45qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
46 qPrintable(objectName()), newPrecision);
48
49
51class MainWindow : public QMainWindow
52{
53public:
54 MainWindow();
55
56protected:
57 bool eventFilter(QObject *obj, QEvent *ev) override;
58
59private:
60 QTextEdit *textEdit;
61};
62
64{
65 textEdit = new QTextEdit;
66 setCentralWidget(textEdit);
67
68 textEdit->installEventFilter(this);
69}
70
72{
73 if (obj == textEdit) {
74 if (event->type() == QEvent::KeyPress) {
75 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
76 qDebug() << "Ate key press" << keyEvent->key();
77 return true;
78 } else {
79 return false;
80 }
81 } else {
82 // pass the event on to the parent class
84 }
85}
87
88
92
93
95class MyObject : public QObject
96{
98
99public:
100 MyObject(QObject *parent = nullptr);
101
102protected:
103 void timerEvent(QTimerEvent *event) override;
104};
105
107 : QObject(parent)
108{
109 startTimer(50); // 50-millisecond timer
110 startTimer(1000); // 1-second timer
111 startTimer(60000); // 1-minute timer
112
113 using namespace std::chrono;
114 startTimer(milliseconds(50));
115 startTimer(seconds(1));
116 startTimer(minutes(1));
117
118 // since C++14 we can use std::chrono::duration literals, e.g.:
119 startTimer(100ms);
120 startTimer(5s);
121 startTimer(2min);
122 startTimer(1h);
123}
124
126{
127 qDebug() << "Timer ID:" << event->timerId();
128}
130
131
133QPushButton *button = parentWidget->findChild<QPushButton *>("button1");
135
136
138QListWidget *list = parentWidget->findChild<QListWidget *>();
140
141
143QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>("widgetname");
145
146
148QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>();
150
151
153monitoredObj->installEventFilter(filterObj);
155
156
158class KeyPressEater : public QObject
159{
161 ...
162
163protected:
164 bool eventFilter(QObject *obj, QEvent *event) override;
165};
166
168{
169 if (event->type() == QEvent::KeyPress) {
170 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
171 qDebug("Ate key press %d", keyEvent->key());
172 return true;
173 } else {
174 // standard event processing
176 }
177}
179
180
185
187listView->installEventFilter(keyPressEater);
189
190
192MyWindow::MyWindow()
193{
194 QLabel *senderLabel = new QLabel(tr("Name:"));
195 QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
197}
198
199
201if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
203 get_the_value(&data); // expensive operation
204 emit valueChanged(data);
205}
207
208
212QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
213 label, SLOT(setNum(int)));
215
216
218// WRONG
219QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
220 label, SLOT(setNum(int value)));
222
223
225class MyWidget : public QWidget
226{
228
229public:
230 MyWidget();
231
232signals:
234
235private:
236 QPushButton *myButton;
237};
238
240{
241 myButton = new QPushButton(this);
242 connect(myButton, SIGNAL(clicked()),
243 this, SIGNAL(buttonClicked()));
244}
246
247
250(Make sure 'MyType' is registered using qRegisterMetaType().)
252
253
254
255disconnect(myObject, nullptr, nullptr, nullptr);
257
258
262
263
265disconnect(myObject, SIGNAL(mySignal()), nullptr, nullptr);
267
268
272
273
275disconnect(myObject, nullptr, myReceiver, nullptr);
277
278
280myObject->disconnect(myReceiver);
282
283
285if (signal == QMetaMethod::fromSignal(&MyObject::valueChanged)) {
286 // signal is valueChanged
287}
289
290
292void on_<object name>_<signal name>(<signal parameters>);
294
295
299
300
302class MyClass : public QObject
303{
305 Q_CLASSINFO("Author", "Pierre Gendron")
306 Q_CLASSINFO("URL", "http://www.my-organization.qc.ca")
307
308public:
309 ...
310};
312
314Q_PROPERTY(QString title READ title WRITE setTitle USER true)
316
317
319class MyClass : public QObject
320{
322
323public:
324 MyClass(QObject *parent = nullptr);
326
327 enum Priority { High, Low, VeryHigh, VeryLow };
328 Q_ENUM(Priority)
330 Priority priority() const;
331};
333
334
337{
339
340public:
341 ...
343 NoUpdate = 0x0000,
344 Clear = 0x0001,
345 Select = 0x0002,
346 Deselect = 0x0004,
347 Toggle = 0x0008,
348 Current = 0x0010,
349 Rows = 0x0020,
350 Columns = 0x0040,
351 SelectCurrent = Select | Current,
352 ToggleCurrent = Toggle | Current,
353 ClearAndSelect = Clear | Select
354 };
355
356 Q_DECLARE_FLAGS(SelectionFlags, SelectionFlag)
357 Q_FLAG(SelectionFlags)
358 ...
359}
361
362
366
367
369QListWidget *list = parentWidget->findChild<QListWidget *>(Qt::FindDirectChildrenOnly);
371
372
374QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *>(Qt::FindDirectChildrenOnly);
376
378QLabel *label = new QLabel;
383
385void someFunction();
389
393socket->connectToHost("qt-project.org", 80);
395 socket->write("GET " + page + "\r\n");
396 });
398
400disconnect(myObject, &MyObject::mySignal(), nullptr, nullptr);
402
407
409static const QMetaMethod valueChangedSignal = QMetaMethod::fromSignal(&MyObject::valueChanged);
410if (isSignalConnected(valueChangedSignal)) {
412 data = get_the_value(); // expensive operation
413 emit valueChanged(data);
414}
416
418void someFunction();
422
424QByteArray page = ...;
426socket->connectToHost("qt-project.org", 80);
428 socket->write("GET " + page + "\r\n");
431
433class MyClass : public QWidget
434{
436
437public:
438 MyClass(QWidget *parent = nullptr);
440
441 bool event(QEvent* ev) override
442 {
443 if (ev->type() == QEvent::PolishRequest) {
444 // overwrite handling of PolishRequest if any
445 doThings();
446 return true;
447 } else if (ev->type() == QEvent::Show) {
448 // complement handling of Show if any
449 doThings2();
450 QWidget::event(ev);
451 return true;
452 }
453 // Make sure the rest of events are handled
454 return QWidget::event(ev);
455 }
456};
458
459
461{
462const QSignalBlocker blocker(someQObject);
463// no signals here
464}
466
468const bool wasBlocked = someQObject->blockSignals(true);
469// no signals here
470someQObject->blockSignals(wasBlocked);
472
473{
475 QObject *obj;
476 ...
477 int id = obj->startTimer(100ms);
478 if (id > Qt::TimerId::Invalid)
479 // The timer has been started successfully
480
481 if (id > 0) // Equivalent, albeit less readable
482 // The timer has been started successfully
484}
bool eventFilter(QObject *obj, QEvent *event) override
Filters events if this object has been installed as an event filter for the watched object.
bool eventFilter(QObject *obj, QEvent *ev) override
Filters events if this object has been installed as an event filter for the watched object.
MyClass(QObject *parent=nullptr)
MyClass(QWidget *parent=nullptr)
bool event(QEvent *ev) override
This virtual function receives events to an object and should return true if the event e was recogniz...
void timerEvent(QTimerEvent *event) override
This event handler can be reimplemented in a subclass to receive timer events for the object.
MyObject(QObject *parent=nullptr)
void buttonClicked()
The QAbstractButton class is the abstract base class of button widgets, providing functionality commo...
void clicked(bool checked=false)
This signal is emitted when the button is activated (i.e., pressed down then released while the mouse...
void connected()
This signal is emitted after connectToHost() has been called and a connection has been successfully e...
virtual void connectToHost(const QString &hostName, quint16 port, OpenMode mode=ReadWrite, NetworkLayerProtocol protocol=AnyIPProtocol)
Attempts to make a connection to hostName on the given port.
\inmodule QtCore
Definition qbytearray.h:57
static QCoreApplication * instance() noexcept
Returns a pointer to the application's QCoreApplication (or QGuiApplication/QApplication) instance.
\inmodule QtCore
Definition qcoreevent.h:45
@ PolishRequest
Definition qcoreevent.h:110
@ KeyPress
Definition qcoreevent.h:64
qint64 write(const char *data, qint64 len)
Writes at most maxSize bytes of data from data to the device.
SelectionFlag
This enum describes the way the selection model will be updated.
The QKeyEvent class describes a key event.
Definition qevent.h:424
int key() const
Returns the code of the key that was pressed or released.
Definition qevent.h:434
The QLabel widget provides a text or image display.
Definition qlabel.h:20
void setText(const QString &)
Definition qlabel.cpp:263
The QLineEdit widget is a one-line text editor.
Definition qlineedit.h:28
void textChanged(const QString &)
This signal is emitted whenever the text changes.
The QListView class provides a list or icon view onto a model.
Definition qlistview.h:17
The QListWidget class provides an item-based list widget.
The QMainWindow class provides a main application window.
Definition qmainwindow.h:25
void setCentralWidget(QWidget *widget)
Sets the given widget to be the main window's central widget.
\inmodule QtCore
Definition qmetaobject.h:19
static QMetaMethod fromSignal(PointerToMemberFunction signal)
\inmodule QtCore
Definition qobject.h:103
int startTimer(int interval, Qt::TimerType timerType=Qt::CoarseTimer)
This is an overloaded function that will start a timer of type timerType and a timeout of interval mi...
Definition qobject.cpp:1817
T findChild(QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
Returns the child of this object that can be cast into type T and that is called name,...
Definition qobject.h:155
void installEventFilter(QObject *filterObj)
Installs an event filter filterObj on this object.
Definition qobject.cpp:2339
QObject * parent() const
Returns a pointer to the parent object.
Definition qobject.h:346
static QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
\threadsafe
Definition qobject.cpp:2960
virtual bool eventFilter(QObject *watched, QEvent *event)
Filters events if this object has been installed as an event filter for the watched object.
Definition qobject.cpp:1555
static bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
\threadsafe
Definition qobject.cpp:3236
bool moveToThread(QThread *thread QT6_DECL_NEW_OVERLOAD_TAIL)
Changes the thread affinity for this object and its children and returns true on success.
Definition qobject.cpp:1643
bool inherits(const char *classname) const
Returns true if this object is an instance of a class that inherits className or a QObject subclass t...
Definition qobject.h:348
The QPushButton widget provides a command button.
Definition qpushbutton.h:20
The QScrollBar widget provides a vertical or horizontal scroll bar.
Definition qscrollbar.h:20
Exception-safe wrapper around QObject::blockSignals().
Definition qobject.h:483
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:129
The QTcpSocket class provides a TCP socket.
Definition qtcpsocket.h:18
The QTextEdit class provides a widget that is used to edit and display both plain and rich text.
Definition qtextedit.h:27
\inmodule QtCore
Definition qcoreevent.h:366
\inmodule QtCore
Definition qtimer.h:20
The QVBoxLayout class lines up widgets vertically.
Definition qboxlayout.h:91
The QWidget class is the base class of all user interface objects.
Definition qwidget.h:99
bool event(QEvent *event) override
This is the main event handler; it handles event event.
Definition qwidget.cpp:8866
QPushButton
[1]
myinstance setPriority(MyClass::VeryHigh)
QPushButton * button
[2]
auto signal
QList< QVariant > arguments
@ FindDirectChildrenOnly
@ AutoConnection
@ QueuedConnection
DBusConnection const char DBusError DBusBusType DBusError return DBusConnection DBusHandleMessageFunction void DBusFreeFunction return DBusConnection return DBusConnection return const char DBusError return DBusConnection DBusMessage dbus_uint32_t return DBusConnection dbus_bool_t DBusConnection DBusAddWatchFunction DBusRemoveWatchFunction DBusWatchToggledFunction void DBusFreeFunction return DBusConnection DBusDispatchStatusFunction void DBusFreeFunction DBusTimeout return DBusTimeout return DBusWatch return DBusWatch unsigned int return DBusError const DBusError return const DBusMessage return DBusMessage return DBusMessage return DBusMessage return DBusMessage return DBusMessage return DBusMessageIter int const void return DBusMessageIter DBusMessageIter return DBusMessageIter void DBusMessageIter void int return DBusMessage DBusMessageIter return DBusMessageIter return DBusMessageIter DBusMessageIter const char const char const char const char return DBusMessage return DBusMessage const char return DBusMessage dbus_bool_t return DBusMessage dbus_uint32_t return DBusMessage void
EGLOutputLayerEXT EGLint EGLAttrib value
[5]
#define Q_DECLARE_FLAGS(Flags, Enum)
Definition qflags.h:174
#define qDebug
[1]
Definition qlogging.h:164
constexpr int qRegisterMetaType()
Definition qmetatype.h:1418
#define SLOT(a)
Definition qobjectdefs.h:52
#define SIGNAL(a)
Definition qobjectdefs.h:53
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
GLenum type
GLuint GLsizei const GLchar * label
[43]
GLfloat GLfloat GLfloat GLfloat h
struct _cl_event * event
GLhandleARB obj
[2]
GLdouble s
[6]
Definition qopenglext.h:235
#define qPrintable(string)
Definition qstring.h:1531
#define tr(X)
#define Q_ENUM(x)
#define Q_PROPERTY(...)
#define Q_OBJECT
#define Q_CLASSINFO(name, value)
#define Q_FLAG(x)
#define signals
#define emit
QList< int > list
[14]
if(qFloatDistance(a, b)<(1<< 7))
[0]
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection)
QPushButton * pushButton
static const QMetaMethod valueChangedSignal
[48]
QList< QPushButton * > childButtons
[42]
const bool wasBlocked
[52]
QAbstractButton * button
[8]
void on_button1_clicked()
[33]
QList< QWidget * > widgets
[11]
QVBoxLayout * layout
QLineEdit * lineEdit
QListView * listView
QString title
[35]
QListWidget * list
[10]
QScrollBar * scrollBar
KeyPressEater * keyPressEater
[15]
myObject disconnect()
[26]
void on_< object name > _< signal name >(< signal parameters >)
[32]
QByteArray page
[45]
QTcpSocket * socket
[1]
QList< QPushButton * > allPButtons
[12]
QTimer * timer
[3]
QQueue< int > queue
[0]
g setTitle("&User information")
[0]
qDebug()<< engine.evaluate("myObject.dynamicProperty").toInt()
[1]