Signal and Slot Interview Questions

Q) Where is the body of the signals?
Signals are just simple functions, whose body is generated by moc. They are just calling QMetaObject::activate, with an array of pointers to arguments on the stack. Here is the code of a signal, as generated by moc.
Q) What is the need of proxy and adapater?

STL Vector example in C++ in Linux all operations

//Vector is a STL container. Vector is template type container, which can store any type of element by providing type in template arguments. Vector size expanded to double or shrinks dynamically at run time. Just like array memory is allocated contagiously but unlike array it is stored in heap. 
//vector is should be preferred as compared to dynamic array because
//1.memory is automatically freed in case of vector on destruction
//2.vector is implemented internally as dynamic array in heap which
//shrinks and grows automatically so no wastage of memory
//3. It is fast as elements can be accessed randomly by index just like arrays.
For understanding:
No of elt  size  capasity
0              0       0
1              1       1 
2              2       2
3              3       4
4              4       4
5              5       8
6              6       8
7              7       8
8              8       8 
9              9       16
10           10      16
17            17     32 
Example:       
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
int main()
{
vector<string> myvector;
cout<<"-----"<<"Inserting at end using pushback is efficient in vector as no shift:"<<endl;
myvector.push_back("cccc");
myvector.push_back("bbbb");
myvector.push_back("eeee");
myvector.push_back("aaaa");
myvector.push_back("dddd");
cout<<"-----"<<"Size of the vector is:"<<myvector.size()<<endl;

cout<<"-----"<<"Traversing vector with iterator:"<<endl;
vector<string>::iterator it;
for(it=myvector.begin();it!=myvector.end();it++)
cout<<*it<<" ";//mind the syntax to display//cccc bbbb eeee aaaa dddd

cout<<"\n----"<<"Traversing vector with index subscripts:"<<endl;
for(int i=0;i<myvector.size();i++)
cout<<myvector[i];//mind the syntax to display//cccc bbbb eeee aaaa dddd

cout<<"\n-------"<<"Sorting vector elements in ascending order:"<<endl;
sort(myvector.begin(),myvector.end());
for(it=myvector.begin();it!=myvector.end();it++)
cout<<*it<<" ";//aaaa bbbb cccc dddd eeee

cout<<"\n------------"<<"Finding a string in a vector of strings:"<<endl;
int pos;string elt="bbbb";
pos=find(myvector.begin(),myvector.end(),elt)-myvector.begin();
if(pos<myvector.size())//
cout<<"bbbb found at index:"<<pos<<endl;//bbbb at 1st index
else
cout<<"Not found"<<endl;

cout<<"------------"<<"Vector before erasing is:"<<endl;
for(int i=0;i<myvector.size();i++)
cout<<myvector.at(i);//aaaa bbbb cccc dddd eeee

cout<<"\n------------"<<"Erasing 1st index element ie bbbb of vector"<<endl;
myvector.erase(myvector.begin()+1);//deleting 1st index leaving 0th index elt
cout<<"Now vector is:";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//aaaa cccc dddd eeee

cout<<"\n------------"<<"Erasing first 2 elements:"<<endl;
myvector.erase(myvector.begin(), myvector.begin()+2);//2 elements and not 2 index
cout<<"Now vector is:";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//dddd eeee

cout<<"\n------------"<<"clear deletes all the elts of a vector"<<endl;
//Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
myvector.clear();
for(int i=0;i<myvector.size();i++)
cout<<myvector[i];//empty

cout<<"------------"<<"Inserting method 2 in vector"<<endl;
myvector.push_back("ffff");
myvector.push_back("gggg");

cout<<"------------"<<"pop_back in vector to delete from last"<<endl;
while(!myvector.empty())
{
cout<<myvector.back();//gggg ffff
myvector.pop_back();
}//vector is empty now
cout<<"\nInserting after 0th elt";
vector<string>::iterator itr2=myvector.begin();
myvector.insert(itr2,"bbbb");
myvector.insert(itr2,"pppp");
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//pppp bbbb

cout<<"\nInserting after nth elt";
vector<string>::iterator itr22=myvector.begin();
myvector.insert(itr22+1,"hhhh");//insert hhhh after pppp
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//pppp hhhh bbbb

cout<<"\n------------"<<"Finding other way:"<<endl;
vector<string>::iterator itr;
itr=find(myvector.begin(),myvector.end(),"pppp");
if(itr!=myvector.end())
{
cout<<"pppp found at position:"<<itr-myvector.begin()<<endl;//1
//deleting found element as
myvector.erase(itr);
}
else
{
cout<<"Not found"<<endl;
}
cout<<"After deleting pppp vector becomes:::\n";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];// hhhh bbbb

cout<<"\n------------"<<"Reverse a vecotr:"<<endl;
reverse(myvector.begin(),myvector.end());
for(int i=0;i<myvector.size();i++)
cout<<myvector[i]<<" ";//bbbb hhhh pppp

cout<<"\n------------"<<"insert repeated values"<<endl;
//exchanges elements of vectors even difference in sizes
vector<int> vec1 (3,100);   // three ints with a value of 100
vector<int> vec2 (5,200);   // five ints with a value of 200
vec1.swap(vec2);
for(int i=0;i<vec1.size();i++)
cout<<vec1[i]<<" ";//becomes 200 200 200 200 200

cout<<"\n------------"<<"Delete all occurence of an element from vector"<<endl;
vec1.erase(remove(vec1.begin(), vec1.end(), 200), vec1.end());
for(int i=0;i<vec1.size();i++)
cout<<vec1[i]<<" ";//becomes 200 200 200 200 200

cout<<"\n-------------"<<"Finding and deleting a particular element in a vector."<<endl;
//vector<int> vect3{20,30,40,111,111,11,60};//need to compile with -std=c++11
vector<int> vect3;
vect3.push_back(20);
vect3.push_back(30);
vect3.push_back(40);
vect3.push_back(111);
vect3.push_back(111);
vect3.push_back(11);
vect3.push_back(60);
int count=0;
for( vector<int>::iterator iter = vect3.begin(); iter != vect3.end(); ++iter )
{
count++;
    if( *iter == 111 )
    {
cout<<"111 found at: "<<count<<" and "<<vect3.at(count);
        vect3.erase( iter );
        break;
    }
}
cout<<"\nNow vector is:"<<endl;
for(int i=0;i<vect3.size();i++)
cout<<vect3[i]<<" ";//becomes 20 30 40 111 11 60

cout<<"\n----Find and replace in a vector of integers"<<endl;
int myints[] = { 11, 22, 33, 33, 11, 11, 22, 44,55,66 };
vector<int> myvector2 (myints, myints+10);            // 11 22 33 33 11 11 22 44 55 66
replace (myvector2.begin(), myvector2.end(), 22, 222); // 11 222 33 33 11 11 222 44 55 66

cout << "myvector2 contains:";
for (vector<int>::iterator it=myvector2.begin(); it!=myvector2.end(); ++it)
cout <<" "<< *it;//10 99 30 30 99 10 10 99

cout<<endl;
return 0;
}
/*
OUTPUT:
------------Inserting at end using pushback is efficient in vector as no shift:
------------Size of the vector is:5
------------Traversing vector with iterator:
cccc bbbb eeee aaaa dddd
------------Traversing vector with index subscripts:
ccccbbbbeeeeaaaadddd
------------Sorting vector elements in ascending order:
aaaa bbbb cccc dddd eeee
------------Finding a string in a vector of strings:
bbbb found at index:1
------------Vector before erasing is:
aaaabbbbccccddddeeee
------------Erasing 1st index element ie bbbb of vector
Now vector is: aaaa cccc dddd eeee
------------Erasing first 2 elements:
Now vector is: dddd eeee
------------clear deletes all the elts of a vector
------------Inserting method 2 in vector
------------pop_back in vector to delete from last
ggggffff
Inserting after 0th elt pppp bbbb
Inserting after nth elt pppp hhhh bbbb
------------Finding other way:
pppp found at position:0
After deleting pppp vector becomes:::
 hhhh bbbb
------------Reverse a vecotr:
bbbb hhhh
------------insert repeated values
200 200 200 200 200
------------Delete all occurence of an element from vector

-------------Finding and deleting a particular element in a vector.
111 found at: 4 and 111
Now vector is:
20 30 40 111 11 60

*/
/*Vector is internally implemented as dynamically allocated array.eg. if size is not know then int *p = new in[size].http://www.cplusplus.com/doc/tutorial/dynamic/ Non dynamic array example is int array[SIZE];wastage of unused memory. In dynamic array only pointer to array is static. So vector is used for efficient memory allocation when insert is at last scenarios.
As the vectors use an array as their underlying storage, inserting elements in positions other than the vector end causes the container to relocate all the elements that were after position to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).*/

Qt example for displaying text from line edit to label on button click using signal and slots

//connectButtonClose.pro
#-------------------------------------------------
# Project created by QtCreator
#-------------------------------------------------
QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = connectButtonClose
TEMPLATE = app
SOURCES += main.cpp\
        mainwindow.cpp
HEADERS  += mainwindow.h
FORMS    += mainwindow.ui
//---------------
//main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
   // MainWindow w;
   // w.show();
MainWindow *w = new MainWindow;
w->setUI();
    return a.exec();
}
//-------------
//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QDebug>
#include <QLineEdit>
#include <QLabel>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<endl;
    ui->setupUi(this);

//    qpb =new QPushButton("HitMe");
//    hl = new QHBoxLayout;
//    le = new QLineEdit();
//    label1 =new QLabel;
//    hl->addWidget(le);
//    hl->addWidget(qpb);
//    hl->addWidget(label1);

//    myWidget = new QWidget;
//    myWidget->setLayout(hl);
//    myWidget->show();
//    QObject::connect(qpb,SIGNAL(clicked()),this,SLOT(slotCalled()));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete qpb;
    delete hl;
    delete label1;
}
void MainWindow::setUI()
{
    qpb =new QPushButton("HitMe");
    hl = new QHBoxLayout;
    le = new QLineEdit();
    label1 =new QLabel;
    label2 =new QLabel;
    hl->addWidget(le);
    hl->addWidget(qpb);
    hl->addWidget(label1);
    hl->addWidget(label1);

    myWidget = new QWidget;
    myWidget->setLayout(hl);
    myWidget->show();

    QObject::connect(qpb,SIGNAL(clicked()),this,SLOT(slotCalled()));
    //QObject::connect(qpb,SIGNAL(clicked()),this,SLOT(slotCalled2()));
   // QObject::connect(qpb,SIGNAL(mysignal()),this,SLOT(slotCalled()));
    QObject::connect(this,SIGNAL(mysignal()),this,SLOT(slotCalled2()));
    QObject::connect(this,SIGNAL(mysignal()),this,SLOT(slotCalled3()));//one signal connected with 2 slots gets called in order of connect
}

//void MainWindow::mysignal()
//{
//    qDebug()<<"Signal is called.\n\n\n";
//}
void MainWindow::slotCalled()
{
    qDebug()<<"slotCalled"<<endl;
    //QString data = le->text();
   // qDebug()<<"data"<<data<<endl;
    //label1->setText(data);
    //label1->setText(le->text());
    qDebug()<<"emmitting mysignal from slotCalled()..."<<endl;
    emit mysignal();

}
void MainWindow::slotCalled2()
{
    qDebug()<<"slotCalled2"<<endl;
//    QString data = le->text();
//    qDebug()<<"data"<<data<<endl;
//    label1->setText(data);
    label1->setText(le->text());

}
void MainWindow::slotCalled3()
{
    qDebug()<<"slotCalled3"<<endl;
}

//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QLabel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    QLineEdit *le;
    Ui::MainWindow *ui;
    QPushButton *qpb ;
    QHBoxLayout *hl;
    QWidget *myWidget;
    QLabel *label1;
    QLabel *label2;
public slots:
    void slotCalled();
    void slotCalled2();
    void slotCalled3();
signals:
//    Q_SIGNALS:
    void mysignal();
public:
    void setUI();
};

#endif // MAINWINDOW_H
//mainwindow.ui
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow" >
  <property name="geometry" >
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle" >
   <string>MainWindow</string>
  </property>
  <widget class="QMenuBar" name="menuBar" />
  <widget class="QToolBar" name="mainToolBar" />
  <widget class="QWidget" name="centralWidget" />
  <widget class="QStatusBar" name="statusBar" />
 </widget>
 <layoutDefault spacing="6" margin="11" />
 <pixmapfunction></pixmapfunction>
 <resources/>
 <connections/>
</ui>
//Steps to build: download the source code in a folder. Navigate to the folder. qmake connectButtonClose.pro. then make.

Frequently asked questions in Qt interviews

What is DBus in Qt?

Q)What is D-Bus?
D-Bus is an IPC Mechanism in Linux.
D-Bus allows applications to expose internal API to the outside world by means of remotely callable interfaces.
These APIs can then be accessed at run-time via the D-Bus protocol using command line applications or D-Bus libraries and bindings themselves.
http://www.tune2wizard.com/linux-qt-signals-and-slots-qt-d-bus/
Defintion from others:
D-Bus  is  a  service  daemon  that  runs  in  the  background.  We  use  bus  daemons  to  interact  with  applications  and  their  functionalities.  The  bus  daemon forwards  and  receives  messages  to  and  from  applications.  There  are  two  types  of  bus  daemons:  SessionBus  and  SystemBus.
Before start doing any code, there is some terms that one should be familiar with:
http://linoxide.com/how-tos/d-bus-ipc-mechanism-linux/
http://www.linuxjournal.com/article/10455?page=0,1

Q) is This The Best Way?
Using QDBusMessage directly in this way to invoke remote D-Bus methods is not the easiest, best or even recommend way of doing things.
We will now look at the more convenient QDBusInterface class and then look at accessing remote D-Bus interfaces as if they were local methods using proxy classes auto-generated from XML.
https://techbase.kde.org/Development/Tutorials/D-Bus/Accessing_Interfaces
Note:
//Server/Application1 who will expose its function test() which can be invoked from other application2/client
#. Suppose a application(call server or daemon) willing to expose a function named "test()" in its mainwindow.h to other applications.
#. server app will generate a xml file with mainwindow.cpp containg the function to be exposed.
Command line was: qdbuscpp2xml mainwindow.h -o mainwindow.xml
#. server app will generate adapter .cpp and .h (when remote/client another app calls test of server function in adapter is also called.)
Command line was: qdbusxml2cpp -a test_adap mainwindow.xml
#. Server will create a session/sytem d-bus connection and register "service name" and "object name".(client app must mention these in proxy class object)
    new MainWindowAdaptor(&w);
    QDBusConnection connection = QDBusConnection::sessionBus();
    connection.registerService("manoj.test.service.name");
    connection.registerObject("/manojobjectpathname", &w);


    //test() can be called from client app by mentioning above service name and object name
    LocalMainWindowInterface *m_window = new LocalMainWindowInterface("manoj.test.service.name",
"/manojobjectpathname",
QDBusConnection::sessionBus(),
0);
    qDebug() << "Result from 1# " << m_window->test("via setParent");
#. Servie name: Service is program started by server/daemon to provide some functionality to other program. e.g. "manoj.test.service.name".
#. Object path name: "/manojobjectpathname"
#. Interface: are classes(p.v.f. or abstract class). that contain mehods and signals. Object name "/manojobjectpathname" has the interface "local.MainWindow" having interface class name as "LocalMainWindowInterface" which have method "Test()".

//Client or application2 who want to use function test() of server/daemon/application1
$. Suppose client/app2 wants to use the function test() exposed by the server/daemon/application1.
$. client application will generate proxy/interface files test_interface.cpp and test_interface.h using the mainwindow.xml of server application.
$. proxy files contains the proxy/remote class name "LocalMainWindowInterface" of server/daemon/app2 which contain the exposed function test().
$. From client app1, test() of server app2 can be called by creating object of proxy/remote class "LocalMainWindowInterface" already created in client app by mentioning the "service name" and "object path name".
   LocalMainWindowInterface *m_window = new LocalMainWindowInterface("manoj.test.service.name",
"/manojobjectpathname",
QDBusConnection::sessionBus(),
0);
m_window->test("via setParent");
Download the source code from 
https://github.com/manozsahu/dbusDemo1.git
https://github.com/manozsahu/dbusDemo2.git
You may also like

Qt moc FAQ Interview Questions

Q) What is Qt ?
Qt is a cross-platform application framework that is widely used for developing application software that can be run on various software and hardware platforms with little or no change in the underlying codebase,
Q) What is a framework?
framework  is an essential supporting structure of a building, vehicle, or object.
. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), which is overriden by user.
.Frameworks  is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality
Framework->uses your code.
Library->you use library code.
Q) What is qmake?
qmake is a utility that automates the generation of Makefiles.
Makefiles are used by the program make to build executable programs from source code; therefore qmake is a make-makefile tool, or makemake for short.
QMake does not call g++/gcc directly. Instead, qmake creates native make files on your current platform. Under linux it creates standard GNU make files, under windows it can generate visual studio make files, under Mac OS X it can generate XCode project files. You then invoke your native build system (either GNU make, or MS NMake, or xcodebuild or whatever), which will call your native compiler (g++/gcc or whatever).
Q) What is Qt and Qml ?
Qt is a cross-platform application framework.
QML is the name of the language (just like C++, which is another language...)
QML stands for Qt Meta Language or Qt Modelling Language is a user interface markup language.
QtQuick is a toolkit for QML, allowing to develop graphical interface in QML language (there are other toolkits for QML, some are graphical like Sailfish Silica or BlackBerry Cascade, and some are non-graphical like QBS which is a replacement for QMake/CMake/make...)
QtQuick 1.x was Qt4.x-based and used the QPainter/QGraphicsView API to draw the scene. QtQuick 2.X was introduced with Qt5.0, based on Scene Graph, an OpenGLES2 abstraction layer, highly optimized.
With Qt5.1, Scene Graph was enhanced to use multithreading (QtQuick 2.1) With Qt5.2,
Q)What is Qt's meta object system?
Qt's meta-object system provides the signals and slots mechanism for inter-object communication, run-time type information, and the dynamic property system.
The meta-object system is based on three things:
1. The QObject class provides a base class for objects that can take advantage of the meta-object system.
2. The Q_OBJECT macro inside the private section of the class declaration is used to enable meta-object features, such as dynamic properties, signals, and slots.
3. The Meta-Object Compiler (moc) supplies each QObject subclass with the necessary code to implement meta-object features.
The moc tool reads a C++ source file. If it finds one or more class declarations that contain the Q_OBJECTmacro, it produces another C++ source file which contains the meta-object code for each of those classes.
Q)What is moc? http://doc.qt.io/qt-4.8/moc.html
The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.
The moc tool reads a C++ header file.
1>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.and
2>meta-object code is required for the signals and slots mechanism and
3>moc is required for run-time type information, and the dynamic property system.
Note:
The C++ source file generated by moc must be compiled and linked with the implementation of the class.
But,If you use qmake to create your makefiles, build rules will be included that call the moc when required, so you will not need to use the moc directly.
Q) can moc file handle all class type?
No, class template can not have signal slot. can not be handled by moc.
Q) What are limitations of moc:
moc does not handle all of C++.e.g.
The main problem is that class templates cannot have signals or slots.
Function Pointers Cannot Be Signal or Slot Parameters
Type Macros Cannot Be Used for Signal and Slot Parameters
Nested Classes Cannot Have Signals or Slots
Signal/Slot return types cannot be references
Q) What is Qvariant?
QVariant is a container of variables. It can store variables of different types. Similar in some way to void*. But it provides You information about the stored type.
It can be used for example to return different types of values from a function.
Q)What is moc?
The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions.
The moc tool reads a C++ header file.
1>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.and
2>meta-object code is required for the signals and slots mechanism and
3>moc is required for run-time type information, and the dynamic property system.
Note:
The C++ source file generated by moc must be compiled and linked with the implementation of the class.
But,If you use qmake to create your makefiles, build rules will be included that call the moc when required, so you will not need to use the moc directly.
 http://doc.qt.io/qt-4.8/moc.html

QThread FAQ in Interviews

Q) What is the entry point for qthread?
The run() implementation is for a thread what the main() entry point is for the application.
Q) Different types of thread?
http://blog.debao.me/2013/08/how-to-use-qthread-in-the-right-way-part-1/
http://ynonperek.com/course/qt/threads.html
First:
QThread MyThread;
this->moveToThread(&MyThread);
//”this” makes object of current class to run in thread
MyThread.start();
Second:
Subclass Qthread and override run()
Third:
QtConcurrent::run(this, &Camera::firstStartThreadProc);
OR
QFuture<void> f1 = QtConcurrent::run(this, &CanDTC::readThreadProc);
USAGE-01
#include <QtCore>
class Thread : public QThread
{
private:
    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();
    return a.exec();
}

Q) What happens if Qthread subclas declartion is in cpp and anot in header file?
You need to have a line at the bottom of your source file: #include "main.moc"
That's because the declaration of class Thread isn't in a header - it's in a .cpp file. So by default moc won't run on it. Adding the line does two things:
it signals to qmake and moc that moc has to process the .cpp file
it causes the stuff that moc generates to be pulled in by the compile step
So after adding that line you'll need to rerun qmake so it can update the makefiles to cause main.moc to be generated.

Q) What is the difference between QueuedConnection and normal connection in connect Qt?
// connect signal-slots for decoupling
QObject::connect (this, SIGNAL(setCurrentTaskSignal(int)), this,
    SLOT(SetCurrentTaskSlot(int)), Qt::QueuedConnection);
Note that QueuedConnection doesn't mean that something is in different thread. QueuedConnection means only that when signal is emitted, corresponding slot won't be called directly. It will be queued on event loop, and will be processed when control will be given back to event loop
One uses a queued connection to ensure that the signal will be delivered from within the event loop, and not immediately from the emit site as happens with direct connection. Direct connection is conceptually a set of calls to function pointers on a list. Queued connection is conceptually an event sent to a clever receiver who can execute a function call based on the contents of the event.

Qt.QueuedConnection -> When emitted, the signal is queued until the event loop is able to deliver it to the slot.

Qt.BlockingQueuedConnection -> Same as QueuedConnection, except that the current thread blocks until the slot has been delivered. This connection type should only be used for receivers in a different thread. Note that misuse of this type can lead to dead locks in your application.

Direct signal-slot connection is nothing else but a chain of synchronous or direct C++ function calls.
A queued signal-slot connection is nothing else but an asynchronous function call

Q) When is Qthread begin executing?
QThreads begin executing in run().
By default, run() starts the event loop by calling exec()...".

Q) By whom and when is run() method called in Qthread?
The run() method is called automagically by Qt when the caller calls start() on your thread

Q) How qthread can be used?
To be able to use one of the QThreadPool threads, we have to subclass QRunnable and implement the run() method. After that, we have to create an instance of the QRunnable subclass and pass it to QThreadPool::start().
//start->run->qthread.

Q)Wtat is the main difference between a process and a thread?
The main difference between a process and a thread is that each process is executed in a separate address space, whereas each thread uses the same address space of a process.
A process can have multiple threads.
Threads share the heap, but each thread of execution has its own call stack.

Q) Difference between QThread runnable and QtConcurrent?
QThread provides a low-level class that can be used for explicit creation of long-running threads.
Using QtConcurrent's functional map/filter/reduce algorithms, which apply functions in parallel to each item in a container, you can write a program that automatically takes advantage of the system's multiple cores by distributing the processing across the threads managed by the thread pool. Alternatively, you can use QRunnable as a base class for the Command pattern and schedule work with QtConcurrent::run(). In these cases, you do not need to create threads explicitly or manage them directly – you can simply describe the pieces of work as objects with the right interface.
QtConcurrent runs a pool of threads and it is a higher level API not well-suited to run a large number of blocking operations:
If you have CPU-bound work to do and want to distribute it across multiple cores, you can break up your work into QRunnables and make those thread-safe by following these recomendations.
Distribute the CPU-heavy calculations across multiple threads using QtConcurrent algorithms whenever possible, instead of writing your own QThread code.
Do not access the GUI (this includes any QWidget-derived class, QPixmap, and other graphics-card specific classes) from any thread other than the main thread. This includes read access like querying the text entered into a QlineEdit.

Q) Suppose your application needs to run a function in multiple threads the number of which is more than the number of CPU cores/threads.
 One way is to use QtConcurrent and setting the maximum thread count :
MyClass *obj = new MyClass;
QThreadPool::globalInstance()->setMaxThreadCount(30);
for(int i=0;i<30;i++)
    QtConcurrent::run(obj, &MyClass::someFunction);
Another way is to have multiple objects and move them to different threads using moveToThread :
for(int i=0;i<30;i++)
{
        MyClass *obj = new MyClass;
        QThread *th = new QThread();
        obj->moveToThread(th);
        connect(th, SIGNAL(started()), obj, SLOT(someFunction()) );
        connect(obj, SIGNAL(workFinished()), th, SLOT(quit()) );
        connect(th, SIGNAL(finished()), obj, SLOT(deleteLater()) );
        connect(th, SIGNAL(finished()), th, SLOT(deleteLater()) );
        th->start();
}

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?
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

QSharedPointer
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;
pI1.clear();
// pI2 is still pointing to pI, so it is not deleted
pI2.clear();
// No shared pointers anymore, pI is deleted

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

QWeakPointer:
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;
pI1.clear();
// No shared pointers anymore, pI is deleted
//
// To use the shared pointer, we must "lock" it for use:
QSharedPointer<int> pI2_locked = pI2.toStrongRef();
Q_ASSERT(pI2_locked.isNull());

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();
connection1.registerService("com.testServiceName");
connection1.registerObject("/testObjectPath",&w);
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)
slot3(int)
slot4()
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
{
Q_OBJECT
protected:
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.
exec();
}
};
SampleThread aThread;
// start thread
aThread.start();
// 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
aThread.quit();
aThread.wait();
// 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
{
private:
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();
}
/*output:
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.

Example:
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.
Steps:
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
{
Q_OBJECT
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.

//timer.moveToThread(&t);
worker.moveToThread(&t);

t.start();

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
29
test.txt contains: 29 characters including spaces and \0


Casting:
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.


1)
#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?