vertopal.com_qt-cheatsheet
vertopal.com_qt-cheatsheet
Index
1. QString
2. QTextStream
3. Taking Commandline Arguments
4. Making a basic QT class with signals and slots
5. Basic QT Dialog with Button, Label and MessageBox
6. Resource File
7. Creating Actions for Menu Bar, Tool Bar
8. Basic QMainWindow with Central Widget, Menu Bar, Tool Bar
9. QList, QStringList, QStringList::iterator, QListIterator
10. QDir, QFileInfo, QDirIterator
11. QFile
12. QDate
13. QThread
14. Serial Ports in QT
15. Short GUI for Sending Characters to Arduino
QString
QString hello = "Hello, World";
QString text = QString(I have %1 taka!).arg(10);
QString *textPtr = new QString("A Beautiful Text");
qDebug() << hello << "\n";
QTextStream
QString qstr;
QTextStream cout(stdout); /* stream text to stdout */
QTextStream cin(stdin); /* take input from stdin */
QTextStream toStringObject(&qstr); /* store in a Qstring */
QString inputString;
cin >> inputString;
cout << inputSting;
main.cpp
#include <QCoreApplication>
#include <QStringList>
#include <QDebug>
return EXIT_SUCCESS;
}
Project file.
simple.pro
TEMPLATE = app # Type. Can be lib, subdir etc
TARGET = simple # Executable name
QT += core
INCLUDEPATH += .
HEADERS =
SOURCES = main.cpp
MyString.h
#ifndef MYSTRING_H
#define MYSTRING_H
#include <QObject>
#include <QString>
class MyString: public QObject{
Q_OBJECT
private:
QString m_text;
public:
MyString(const QString& text, QObject *parent = 0);
public slots:
void setText(const QString&);
signals:
void textChanged(const QString&);
};
#endif
MyString.cpp
#include <QObject>
#include <QString>
#include "MyString.h"
m_text = text;
emit textChanged(m_text);
}
main.cpp
#include <QObject>
#include <QDebug>
#include "MyString.h"
int main(){
QObject parent;
MyString *a, *b;
return 0;
}
mydialog.h
#ifndef __DIALOG_H__
#define __DIALOG_H__
#include <QDialog>
#include <QObject>
Q_OBJECT
public:
MyDialog();
public slots:
void blueClicked();
void redClicked();
};
#endif
mydialog.cpp
#include "mydialog.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QLabel>
MyDialog::MyDialog(){
resize(300, 400);
btnLayout->addWidget(blue);
btnLayout->addStretch();
btnLayout->addWidget(red);
lblLayout->addStretch();
mainLayout->addStretch();
mainLayout->addLayout(btnLayout);
mainLayout->addStretch();
void MyDialog::blueClicked(){
QMessageBox::information(this, "Your Choice", "Welcome to
Matrix!");
}
void MyDialog::redClicked(){
QMessageBox::information(this, "Your Choice", "Good Bye!");
}
main.cpp
#include <QApplication>
#include "mydialog.h"
MyDialog mdlg;
mdlg.show();
return app.exec();
}
Resource File
resource file is used to keep track of the resources used in the application. For resource file
root is the project folder. Lets say we have kept new.png, cut.png and close.png int the
images folder under project folder. We will add these to qt resource file. resource file’s file
extension is qrc.
resources.qrc
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file alias="new">images/new.png</file>
<file alias="cut">images/cut.png</file>
<file alias="close">images/close.png</file>
</qresource>
</RCC>
use: QIcon(“:/images/new.png”)
project.pro
RESOURCES += resources.qrc
mywindow.h
#ifndef __MY_WINDOW_H__
#define __MY_WINDOW_H__
#include <QMainWindow>
#include <QOBject>
class QAction;
class QTextEdit;
Q_OBJECT
private:
QAction *actionNew;
QAction *actionCut;
QAction *actionAbout;
QAction *actionClose;
QTextEdit *editText;
void setupActions();
void setupMenu();
void setupToolBar();
public:
MyWindow();
public slots:
void newFile();
void cut();
};
#endif
mywindow.cpp
#include <QMainWindow>
#include <QAction>
#include <QString>
#include <QTextEdit>
#include <QAction>
#include <QMenu>
#include <QMenuBar>
#include <QToolBar>
#include <QApplication>
#include "mywindow.h"
MyWindow::MyWindow(){
setWindowTitle(QString("Untitled[*]"));
setCentralWidget(editText);
connect(editText->document(), SIGNAL(modificationChanged(bool)),
this, SLOT(setWindowModified(bool)));
setupActions();
setupMenu();
setupToolBar();
}
void MyWindow::setupActions(){
actionNew = new QAction(tr("New"), this);
actionNew->setShortcut(tr("Ctrl+N"));
actionNew->setStatusTip(tr("Open a new document"));
void MyWindow::setupMenu(){
QMenu *fileMenu = menuBar()->addMenu(tr("File"));
fileMenu->addAction(actionNew);
fileMenu->addSeparator();
fileMenu->addAction(actionClose);
toolBar->addAction(actionNew);
toolBar->addSeparator();
toolBar->addAction(actionCut);
}
void MyWindow::newFile(){
void MyWindow::cut(){
main.cpp
#include <QApplication>
#include "mywindow.h"
MyWindow mainwindow;
mainwindow.show();
return app.exec();
}
int main(){
QString heavy = "Metallica, Stentorian, Aurthohin";
QString alt = "Icons, Karnival, Nemesis";
QString symphonic = "Ionic, Eluveitie";
QStringList bands;
bands << heavy << alt << symphonic;
for(QStringList::iterator it = bands.begin();
it != bands.end(); it++){
qDebug() << QString("[[%1]]").arg(*it);
}
QListIterator<QString> it(singleBandList);
while(it.hasNext()){
qDebug() << QString("{%1}").arg(it.next());
}
return 0;
}
dir.setSorting(QDir::Name);
#include <QCoreApplication>
#include <QStringList>
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <QTextStream>
QTextStream cout(stdout);
QTextStream cerr(stderr);
if(!dir.exists()){
cerr << dir.path() << " doesn't exist!\n";
return -1;
}
return EXIT_SUCCESS;
}
QFile
QFile file("myTextFile.txt");
file.open(QIODevice::WriteOnly);
QTextStream outFile(&file);
outFile << "Hello, World!" << "\n";
file.close();
QFile file("myTextFile.txt");
if(file.open(QIODevice::ReadOnly)){
QStringSteam inFile(&file);
QString text;
QDate
QDate::currentDate() returns current date
QThread
Make a custom class inherited from QThread. Override Thread::run() method which will
do the heavy works. Each thread is started with Thread::start() method.
main.cpp
#include <QCoreApplication>
#include "mythread.h"
th1.start();
th2.start();
th3.start();
return app.exec();
}
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QString>
public:
explicit MyThread(QString str);
void run();
private:
QString name;
};
#endif
mythread.cpp
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QString s)
: name(s)
{
}
void MyThread::run(){
for(int i = 0; i <= 100; i++){
qDebug() << this->name << ":" << i;
}
}
Serial Ports in QT
QSerialPortInfo
QList<QSerialPortInfo> QSerialPortInfo::availablePorts() - availablePorst()
static function returns a list of available devices. Available devices are returned as
QSerialPortInfo object
Functions:
QString portName() - Return device port name. E.g ttyACM0, ttyUSB0 QString
systemLocation() - Returns port path / location. E.g /dev/ttyACM0 QString
description - Returns device description. QString manufacturer - Returns device
manufacturer. QString serialNumber() - Return device serial number. bool
hasProductIdentifier() - True if the device has valid product identifier number.
quint16 productIdentifier() - Returns product identifier number. bool
hasVendorIdentifier() - Returns true if the device has valid product number. quint16
vendorIdentifier() - Returns vendor identifier number. bool isBusy() - returns
True if the serial port is busy.
ping arduino
main.cpp
#include <QApplication>
#include "dialog.h"
return app.exec();
}
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QSerialPort>
class QLabel;
class QPushButton;
class QComboBox;
class QLineEdit;
public:
Dialog(QWidget *parent = 0);
public slots:
void connect();
void send();
void handlePortError(const QString &error);
void handleResponse();
signals:
void portError(const QString &error);
private:
QLabel *portLabel;
QComboBox *portComboBox;
QPushButton *connectButton;
QLabel *dataLabel;
QLineEdit *dataLineEdit;
QPushButton *sendButton;
QLabel *statusLabel;
QLabel *status;
QLabel *replyLabel;
QLabel *reply;
QSerialPort serialPort;
};
#endif
dialog.cpp
#include "dialog.h"
#include <QLabel>
#include <QPushButton>
#include <QComboBox>
#include <QLineEdit>
#include <QGridLayout>
#include <QSerialPortInfo>
#include <QByteArray>
#include <QDebug>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, portLabel(new QLabel("Port:"))
, portComboBox(new QComboBox())
, connectButton(new QPushButton("Connect"))
, dataLabel(new QLabel("Data:"))
, dataLineEdit(new QLineEdit())
, sendButton(new QPushButton("Send"))
, statusLabel(new QLabel("Status:"))
, status(new QLabel())
, replyLabel(new QLabel("Reply:"))
, reply(new QLabel())
{
QList<QSerialPortInfo> infos = QSerialPortInfo::availablePorts();
for(const QSerialPortInfo &info : infos){
portComboBox->addItem(info.portName());
}
void Dialog::connect(){
if(serialPort.isOpen()){
serialPort.close();
connectButton->setText("Connect");
return;
}
serialPort.setPortName(portComboBox->currentText());
serialPort.setBaudRate(QSerialPort::Baud9600);
if(!serialPort.open(QIODevice::ReadWrite)){
emit portError(QString("Error:
%1").arg(serialPort.errorString()));
return;
}
status->setText(QString("Connected to
%1.").arg(serialPort.portName()));
connectButton->setText("Disconnect");
return;
}
void Dialog::send(){
QByteArray ba = dataLineEdit->text().toLocal8Bit();
if(ba.isEmpty()){
status->setText(QString("No data!"));
return;
}
if(bytesWritten == -1){
emit portError(QString("Write failed!
%1").arg(serialPort.errorString()));
return;
}
else if(bytesWritten != ba.size()){
emit portError(QString("Can't write all data!
%1").arg(serialPort.errorString()));
return;
}
status->setText(QString("%1 bytes
written!").arg(bytesWritten));
}
return;
}
void Dialog::handleResponse(){
if(serialPort.isOpen() && serialPort.isReadable()){
QByteArray readData = serialPort.readAll();
while(serialPort.waitForReadyRead(5000)){
readData += serialPort.readAll();
}
reply->setText(readData);
return;
}