Frequently asked questions in Qt interviews

FAQ in Qt interviews:
Q) What is Qt?
Qt is a Framework that comprises of several classes that form the Qt object model. The root of this model is the QObject class. Basically all Qt objects inherit from the QObject class. Having inherited from this class, it means all Qt Objects inherit a particular behavior and we can exploit this in order to manage memory.
Q) How qt differs from other mobile development platforms like android?
i)Qt is platform independent- same source code can be used for development for multiple environment with no or very less code change. Android can be used in android environment only.
ii)Language independent- For development in Qt many languages like C++,C#,Java can be used. But in android Java is used.
Q) What are the striking features of QT?
Qt is cross platform application development framework using which application can be developed for different platform with no very less change in codebase.
Few features are:
Signal slots, moc, Qt D-bus,QtCore,QtWidget,QtGui,QML,QtMultimedia,Qt Network, Qt SQL, Qt xml.
Q) What is Qpointer?
It will be automatically set to nullptr if the pointed to object is destroyed. It is a weak pointer specialized for QObject.QPointer can only point to QObject instances.
You would normally use QPointer in a situation where the pointer is being created outside of a QObject class such as in the main function or other none Qt based classes you may have created in your code.
The QPointer is a template class that wraps obj as a pointer to MyObject. You will notice that there is no star to mark it as a pointer because QPointer abstracts all that. It does not just stop there but it also deals with dynamically destroying the obj pointer should there no longer be any references to it.

There you have it. A simple and safer way to use pointers and to manage your memory when programming in Qt C++.

Consider this fragment:

QObject *obj = new QObject;
QPointer<QObject> pObj(obj);
delete obj;
Q_ASSERT(pObj.isNull()); // pObj will be nullptr now

A reference-counted pointer. The actual object will only be deleted, when all shared pointers are destroyed. Equivalent to std::shared_ptr.

int *pI = new int;
QSharedPointer<int> pI1(pI);
QSharedPointer<int> pI2 = pI1;
// pI2 is still pointing to pI, so it is not deleted
// No shared pointers anymore, pI is deleted

Note that as long there is a shared pointer, the object is not deleted!

Can hold a weak reference to a shared pointer. It will not prevent the object from being destroyed, and is simply reset. Equivalent to std::weak_ptr, where lock is equivalent to toStrongRef.

int *pI = new int;
QSharedPointer<int> pI1(pI);
QWeakPointer<int> pI2 = pI1;
// No shared pointers anymore, pI is deleted
// To use the shared pointer, we must "lock" it for use:
QSharedPointer<int> pI2_locked = pI2.toStrongRef();

This can be used if you need access to an object that is controlled by another module.

To use a weak pointer, you must convert it to a QSharedPointer. You should never base a decision on the weak pointer being valid. You can only use data() of isNull to determine that the pointer is null.
Q) What is dpointer?
The d-pointer
The trick is to keep the size of all public classes of a library constant by only storing a single pointer. This pointer points to a private/internal data structure that contains all the data. The size of this internal structure can shrink or grow without having any side-effect on the application because the pointer is accessed only in the library code and from the application's point of view the size of the object never changes - it's always the size of the pointer. This pointer is called the d-pointer.
Q) What is MVC architecture? How it is organized?
MVC consists of three kinds of objects.
Model is the application object,
View is its screen presentation, and the
Controller defines the way the user interface reacts to user input.
Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse.
Model/view architecture to manage the relationship between data and the way it is presented to the user.
Q) What is a signal? And how will it differ from event?
Signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them.
signals: /* signals must be declared under 'signals:' or “ Q_SIGNALS:” access specifier */
void foo(); /* This is a signal declaration -- a pure declaration as a method.*/
Before Qt5 signals were protected so that only same class objects acan emit it.
From Qt5 onwards signals are public and to make it private need to declare QPrivateSignal dummy (empty) struct private in the Q_OBJECT macro.

In Qt, events are objects, derived from the abstract QEvent class, that represent things that have happened either within an application or as a result of outside activity that the application needs to know about. Events can be received and handled by any instance of a QObject subclass, but they are especially relevant to widgets. This document describes how events are delivered and handled in a typical application. in general an event will be generated by an outside entity (e.g. Keyboard, Mouswheel) and will be delivered through the event loop in QApplication.

Signals and Slots are a convenient way for QObjects to communicate with one another and are more similar to callback functions. In most circumstances, when a "signal" is emitted, any slot function connected to it is called directly. The exception is when signals and slots cross thread boundaries. In this case, the signal will essentially be converted into an event.

Q) What is a slot? And how it differs with callback Method?
Slots are normal C++ member functions and can be called normally; their only special feature is that signals can be connected to them. A slot is called when a signal connected to it is emitted. We can also define slots to be virtual.

Callbacks have two fundamental flaws: Firstly, they are not type-safe. We can never be certain that the processing function will call the callback with the correct arguments. Secondly, the callback is strongly coupled to the processing function since the processing function must know which callback to call.

Q) How many signals at maximum you can connect to a single slot? If more than one how you can do that?
Surely we can connect more than one signal to a single slot. The single slot is called whenever one of those connected signal is emmitted.
Even one signal can be coonected to another signal, which are then emitted automatically whenever the source signal is emitted. Definition for signals are genereated in by moc in code generated by moc.
Q) How many slots can you connect to a signal? If more than one how those slots will be executed?
(The order of execution).
Surely more than on slot can be connected to a single signal. Then Slots are called in the order they are connected when the signal is emmitted.
Q) What is QCast and how will it differ compared to c++’s dynamic cast?
qobject_cast function is used to convert polymorphic pointers on qobject classes.
qobject_cast does not reauire the support for rri while dynamic_cast requires to enable rtti.
Similar to dyanimc_cast it returns a non zero pointer on success ad 0 on failure.

For example,
let's assume MyWidget inherits from QWidget and is declared with the Q_OBJECT macro:
class MyWidget: public Qwidget
QObject *obj = new MyWidget;
The cast from QObject to QWidget must be successful, because the object obj is actually a MyWidget, which is a subclass of QWidget.

QWidget *widget = qobject_cast<QWidget *>(obj);

The cast from QObject to QWidget is successful, because the object is actually a MyWidget, which is a subclass of QWidget. Since we know that obj is a MyWidget, we can also cast it to MyWidget.

Q) What is the use of Q_OBJECT macro?
OBJECT simply tells the pre-compiler that this class has gui elements and needs to be run through the 'moc' . In turn moc generates definitions for member variables and functions that Q_OBJECT has declared. moc produces a C++ source file containing the meta-object code for those classes which declare Q_OBJECT and derived from QOBJECT or wants to use signal slot or wants to use qobject_cast.
The Q_OBJECT macro must appear in every class that derives from QObject or which wants to use signal slot mechanism, that want to use qobject_cast.

Q) What is MOC and UIC? Explain how they will work for compilation in QT?
The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.
The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information qobject_cast, and the dynamic property system.
Q) What is qmake? (Explain the usage of it)
Q) How a QT Program/Application written for one platform (Symbian) can be ported/executed in another
platform (Maemo)? (Explain If you need to make any changes or you need to recompile)
Q) What are all the platforms/OS currently QT supports?
Q) What is event loop in Qt?
18) How to design your own widget in Qt?
1).Signal/slot mechanism is synchronous or not? If it is,that means we should not let a slot do much work,otherwise the UI will be blocked for much time.?
Usually, slots are synchronous. Starting with Qt4, you can send signals across threads. If you execute a slot in another thread, you will get an asynchronous slot.
2).QEvent is asynchronous or not? For example ,if I call the update() function,the paintEvent() will be called, if it is asychronous,the UI will not be blocked.?
QEvents are syncronous but you can also deliver events in different slots. With Qt3, this was the only option to invoke something in a different thread.
3).Is there any relationship between signal/slot and event? Does Qt put the slots into event queue?
With Qt4, you can tell Qt to post signals in the event queue using the 5th argument of the connect-method.
1)Memory leak?
Memory leaks occur when pointers referencing a certain chunk of memory goes out of scope and therefore the pointer is lost but the content that the pointer was referencing is still lying in the heap. A pointer would normally go out of scope when an execution block ends and returns and the pointer created within that scope is not destroyed along with the referenced data. This can also occur when an exception is thrown or when any sort of error stops execution before the pointer is destroyed.
Qpointer is used in Qt framework to avoid such scenarios.

QPointer – This tracks the lifetime of an instance of QObject.
QSharedPointer, QWeakPointer – These are thread-safe sharing pointers, similar to C++11’s std::shared_ptr. QWeakPointer use has been deprecated unless used with QSharedPointer.
QScopedPointer, QScopedPointerArray – These are none shared pointers Ideal for Resource Acquisition Is Initialization (RAII) usage whereby they take ownership of a pointer and ensures it is properly deleted at the end of the scope.

Q ) What is D-Bus?
  • D-bus is inter process communication mechanism using which applications can communicate to each other.
  • Using dbus an application exposes its services with adapters.
  • Another application can use the services of other application using proxy by making it d-bus enabled.
Q) What is a System Bus?
  • Generally system bus starts with system's startup level.
  • Mainly used with hardwares events(like keyboard press or mouse click).
  • Event/interrupts/signals are signals from hw/sw to os/processor that it requirs quick attention from os/processor.
Q) What is a Session Bus?
  • Generally session bus starts when a user logins to desktop.
  • Mainly used for desktop applications to connect to each other.
Q) What is the syntax of a dbus?
Application one that exposes its services (say test()) creates xml using cpp2xml tool then creates adapter and proxy using xmltocpp tool and finally include adapter, registerService and registerObject.
new MainWindowAdaptor(&w);
QDBusConnection connection1 = QDBusConnection::sessionBus();
Another applicationTwo which wants to call services/methods exposed by the applicationOne include proxy, create proxy object and call the remote function on proxy object and in turn actual function in remote applicationOne gets called.
MyInterfaceClass * m_window = new MyInterfaceClass("com.testServiceName","/testObjectPath",QDBusConnection::sessionBus(),0);

Then call the function “test()” on remote application using local proxy objext as
m_window->test("via setParent");

Note:instead of 0 specific methods can be given.

Q) How to debug if a connect fails?
  • Check that classes using signals and slots inherit QObject or a QObject subclass.
  • Make sure the Q_OBJECT macro is inserted at the beginning of your class declaration.
  • If you use custom signals, check that these are declared correctly, with a void return type, in the public/protected/private signals section of your class declaration.
  • Make sure that your slot function is declared as a slot, e.g. private slots not private.
  • Put all connect statements before functions calls
  • Check the return value of the connect statement: connect returns true if it successfully connects the signal to the slot.
  • Use QErrorMessage::qtHandler() or qInstallMsgHandler() to view connect error warnings.
  • Put qDebug to check signal slots are called.
  • Check the compiler warnings.
Q) Can we give definition to user defined signal?
No, it will be a redefinition linker error because definition of signal is given in moc code.
Q) Can we connect a signal with another signal?
Yes, as both ara functions.
Example suppose a library code writeCode() emits a signal writeCompleted.
If another code say writeSocket uses the writeCode. On completion it emits another signal say writeSocketCompleted. So we can connect the signal writeSocketCompleted with writeCompleted.(without changing the library code)
Q) can slot have lesser arguments than signal? Yes
The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.)
This means that a signal of the form
signal(int, int, QString)
can only be connected with slots with the following signatures
slot1(int, int, QString)
slot2(int, int)
Q) can we overload function on basis of extern?
No, redefinition.
Q) Why multithreading is used?
1) efficient program to make best use of cpu cycles.
2) handling event driven code in ntworked, gui based, distributed code.
3) threads does not required ipc(like pipe,fifo,socket used in processes to communicate).
4)since threads run on the same address space of process so fast to create.
5) concurrent programming.

Q) How to use thread in Qt. Two ways?
1) creating a sub-class of QThread and implementing the run method then create object of this class and call start on that. Its old style like in java.
class SampleThread : public QThread
virtual void run()
// do some work
qDebug() << "Hello from SampleThread: Thread Id:" << QThread::currentThreadId();
// Enters the main event loop and waits until exit() is called.
SampleThread aThread;
// start thread
// check if thread running, returns true
qDebug()<< "thread running " << aThread.isRunning();
// check if thread finished, returns false
qDebug()<< "thread finished" << aThread.isFinished();
// terminate thread and wait for termination
// check if thread running, returns false
qDebug()<< "thread running " << aThread.isRunning();
// check if thread finished, returns true
qDebug()<< "thread finished" << aThread.isFinished();

Qii) can thread be connected to slots? Yes.
#include <QtCore>
class Thread : public QThread
void run()
qDebug()<<"From worker thread: "<<currentThreadId();

int main(int argc, char *argv[])
QCoreApplication a(argc, argv);
qDebug()<<"From main thread: "<<QThread::currentThreadId();

Thread t;
QObject::connect(&t, SIGNAL(finished()), &a, SLOT(quit()));

t.start(); //start() calls the run() which is the entry point for a thread.
return a.exec();
From main thread: 0x15a8
From worker thread: 0x128c

2)Second way or new way of creating thread. more elegant way.
Subclass QThread and reimplement its run() function is intuitive and there are still many perfectly valid reasons to subclass QThread, but when event loop is used in worker thread, it's not easy to do it in the subclassing way.
Use worker objects by moving them to the thread is easy to use when event loop exists, as it has hidden the details of event loop and queued connection.

  1. Thread affinity was introduced at the base level of QObject, which is the base object for nearly all Qt related classes.
  2. Signal and slot connections can now be used between objects of different thread affinity.
3. QThread gained a default run implementation.

Usage 2-0

If we only want to make use of QThread::exec(), which has been called by QThread::run() by default, there will be no need to subclass the QThread any more.
Create a Worker object
Do signal and slot connections
Move the Worker object to a sub-thread
Start thread

#include <QtCore>

class Worker : public QObject
private slots:
void onTimeout()
qDebug()<<"Worker::onTimeout get called from?: "<<QThread::currentThreadId();

#include "main.moc"
int main(int argc, char *argv[])
QCoreApplication a(argc, argv);
qDebug()<<"From main thread: "<<QThread::currentThreadId();

QThread t;
QTimer timer;
Worker worker;

QObject::connect(&timer, SIGNAL(timeout()), &worker, SLOT(onTimeout()));
timer.start(1000); //start() calls Qthread::run() which is the entry point for thread.



return a.exec();

The result is:As expected, the slot doesn't run in the main thread.
From main thread: 0x1310
Worker::onTimeout get called from?: 0x121c
Worker::onTimeout get called from?: 0x121c
Worker::onTimeout get called from?: 0x121c
Q) Command to count characters without opening it?
/prac$ wc -m < test.txt
test.txt contains: 29 characters including spaces and \0

1) reinterpret_cast: used for i) casting between pointers of unrelated classes. ii) for ptr to int type cast.
2) const_cast: used to remove constantness.
3) dynamic_cast: is used to perform safe downcasting. Base ptr to derived class pointer.
4)static_cast: for implicit type conversions
i)non-const object to const,
ii) int to double.
iii) void* pointers to typed pointers,
iv)base pointers to derived pointers.
But it cannot cast from const to non-const object. This can only be done by const_cast operator.

#include <iostream>
using namespace std;

struct data {
short a;
short b;

int main () {
long value = 0xA2345678;
data* pdata = reinterpret_cast<data*> (&value;);
cout << pdata->a << endl;
return 0;
Output on my machine: 22136 which is 2 bytes of value.

Another example might be:

class A {};
class B {};

int main()
A * pA = new A;
B * pB = reinterpret_cast<B*>(pA);
Qt example for displaying text from line edit to label on button click using signal and slots

What is DBus in Qt?

1 comment:

  1. This comment has been removed by the author.