KDELibs4Support

qtest_kde.cpp
1 /* This file is part of the KDE libraries
2  Copyright (C) 2006 David Faure <[email protected]>
3 
4  This library is free software; you can redistribute it and/or
5  modify it under the terms of the GNU Library General Public
6  License version 2 as published by the Free Software Foundation.
7 
8  This library is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  Library General Public License for more details.
12 
13  You should have received a copy of the GNU Library General Public License
14  along with this library; see the file COPYING.LIB. If not, write to
15  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
16  Boston, MA 02110-1301, USA.
17 */
18 
19 #include "qtest_kde.h"
20 
21 #include <QTimer>
22 
23 // A signal spy which exits the event loop when the signal is called,
24 // and remembers that the signal was emitted.
25 class KDESignalSpy : public QObject
26 {
27  Q_OBJECT
28 public:
29  KDESignalSpy(QObject *obj, const char *signal, int timeout)
30  : QObject(nullptr), m_obj(obj), m_emitted(false)
31  {
32  connect(obj, signal, this, SLOT(slotSignalEmitted()));
33  if (timeout > 0) {
34  QObject::connect(&m_timer, SIGNAL(timeout()), &m_loop, SLOT(quit()));
35  m_timer.setSingleShot(true);
36  m_timer.start(timeout);
37  }
38  m_loop.exec();
39  }
40  bool signalEmitted() const
41  {
42  return m_emitted;
43  }
44 
45 private Q_SLOTS:
46  void slotSignalEmitted()
47  {
48  m_emitted = true;
49  disconnect(m_obj, nullptr, this, nullptr);
50  m_timer.stop();
51  m_loop.quit();
52  }
53 private:
54  QObject *m_obj;
55  bool m_emitted;
56  QEventLoop m_loop;
57  QTimer m_timer;
58 };
59 
60 // Unit test for this code: tests/kglobaltest.cpp
61 
62 bool QTest::kWaitForSignal(QObject *obj, const char *signal, int timeout)
63 {
64  KDESignalSpy spy(obj, signal, timeout);
65  return spy.signalEmitted();
66 }
67 
68 #include "qtest_kde.moc"
bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)
Q_OBJECTQ_OBJECT
Q_SLOTSQ_SLOTS
QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
const QList< QKeySequence > & quit()
This file is part of the KDE documentation.
Documentation copyright © 1996-2021 The KDE developers.
Generated on Sun Jun 20 2021 22:58:15 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.