관리 메뉴

Value Creator의 IT(프로그래밍 / 전자제품)

#22 QT의 시그널과 슬롯(Signal, Slot), Connect 함수 사용법 본문

1. 프로그래밍/3) QT

#22 QT의 시그널과 슬롯(Signal, Slot), Connect 함수 사용법

valuecreatort 2019. 6. 26. 17:56
반응형

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

 

 

1. 시그널 : QPushButton에서 mouse click, double click, mouse over 등과 같이 정의된 것.

 

2. 슬롯 : valueChanged()와 같이 값을 변경하기 위해 제공되는 Virtual 함수.

 

하나의 시그널에는 다수의 슬롯이 연결될 수 있다.

 

마우스 클릭시 값을 변경한다든지 등 여러 변화를 줄 수 있기 때문이다.

 

 

 

QT에는 signal과 slot라는게 있습니다. signal이 발생하면 slot이벤트가 발생합니다.

예)

버튼을 클릭하면 A함수가 실행된다. (SIGNAL : 클릭 , SLOT : A함수)

TCP/IP통신에서 입력받을 데이터가있으면 A함수가 실행된다. (SIGNAL : 입력받을 데이터, SLOT : A함수)

키보드에서 키를 입력하면 라벨이 움직인다. (SIGNAL : 키보드에서 키 입력, SLOT : 라벨움직임)

 

이런식으로 SIGNAL은 이미 만들어진걸 사용할 수도 있고 사용자가 만들 수도 있습니다.

 

 

사용 방법

1. SIGNAL만들기

2. SLOT만들기

3. SIGNAL과 SLOT연결하기 (connect함수)

 


1. SIGNAL만들기

 

SIGNAL을 만들려면 class의 signals한정자 안에 SIGNAL을 선언하면 됩니다.

1

2

signals:

void IamSignals();

cs

만든 SIGNAL은 따로 구현은 안해도 됩니다.

 


2. SLOT만들기

 

1

2

private slots:

void IamSlots();

cs

slot도 똑같은 방법으로 만들어주면 됩니다.

그러나 SLOT은 구현을 해야합니다.

 

 

1

2

3

void MainWindow :: IamSlots(){

qDebug()<< "슬롯 실행";

}

cs

구현은 함수를 구현하는 식으로 똑같이 하면 됩니다.

 


3. SIGNAL과 SLOT연결하기 (connect함수)

QMetaObject::Connection QObject::connect(const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection) [static]

 

connect( SIGNAL이 발생하는 곳 , 발생SIGNAL , SLOT이 발생하는 곳, 발생SLOT)

이런식으로 사용하게 됩니다. 주의할 점은 발생하는 곳의 자료형이 포인터라는 것 입니다.

 

1

connect(this,SIGNAL(IamSignals()),this,SLOT(IamSlots()));

cs

여기에서는 SIGNAL과 SLOT과 connect를 한 클래스 내에서 사용했으므로 this를 사용한 모습입니다.

 

 

signalslot.zip

완성한 파일입니다.


 

 

사실 다른 방법으로도 SIGNAL과 SLOT을 이용 할 수 있습니다.

다양한 클래스에서 이미 SIGNAL과 SLOT가 정의되어 있습니다.

 

예)

소켓통신에서 사용 할 수 있는 SIGNAL입니다.

1

void QIODevice::readyRead() [signal]

cs

서버와 클라이언트가 연결되고, 데이터교환을 할때 수신측에서 사용하는 시그널인데 데이터를 읽을 준비가 되었다는 SIGNAL입니다.

 

QTcpSocket with Signals and Slots

In this tutorial, we will learn how to download a file using QTcpSocket. This is a continued tutorial from the previous one, Qt 5 QTcpSocket. We're going to use Signal and Slot mechanism instead of calling functions manually(?).

Note: Qt5 document

The QTcpSocket class provides a TCP socket.

TCP (Transmission Control Protocol) is a reliable, stream-oriented, connection-oriented transport protocol. It is especially well suited for continuous transmission of data.

QTcpSocket is a convenience subclass of QAbstractSocket that allows you to establish a TCP connection and transfer streams of data. See the QAbstractSocket documentation for details.

For TCP Socket in general, please visit my C++ Tutorials: Socket - Server and Client.

 



QTcpSocket with Signals and Slots

 

In this tutorial, we will learn how to download a file using QTcpSocket. This is a continued tutorial from the previous one, Qt 5 QTcpSocket. We're going to use Signal and Slot mechanism instead of calling functions manually(?).

 

Note: Qt5 document

 

 

 

The QTcpSocket class provides a TCP socket.

 

TCP (Transmission Control Protocol) is a reliable, stream-oriented, connection-oriented transport protocol. It is especially well suited for continuous transmission of data.

 

QTcpSocket is a convenience subclass of QAbstractSocket that allows you to establish a TCP connection and transfer streams of data. See the QAbstractSocket documentation for details.

 

For TCP Socket in general, please visit my C++ Tutorials: Socket - Server and Client.

 

 

 

 

 

 

We'll start with Qt Console Application.

First, we need to add network module to our project file, QTcpSocket.pro:

QT += core

QT += network

QT -= gui

 

TARGET = QTcpSocket

CONFIG += console

CONFIG -= app_bundle

 

TEMPLATE = app

 

 

SOURCES += main.cpp

 

 

Then, we want to create a new class called MyTcpSocket.

 

 

Let's do work on main.cpp.

 

 

 

We need to create an instance of MyTcpSocket, and then call a our key driver function call, doConnect():

// main.cpp

 

#include

#include "mytcpsocket.h"

 

int main(int argc, char *argv[])

{

QCoreApplication a(argc, argv);

 

MyTcpSocket s;

s.doConnect();

 

return a.exec();

}

 

 

Now, let's implement the doConnect() method. But before doing that we should write some lines of code in the mytcpsocket.h:

1.#include

2.the prototype of the method, doConnect()

3.Socket object (pointer)

#ifndef MYTCPSOCKET_H

#define MYTCPSOCKET_H

 

#include

#include

#include

#include

 

class MyTcpSocket : public QObject

{

Q_OBJECT

public:

explicit MyTcpSocket(QObject *parent = 0);

 

void doConnect();

 

signals:

 

public slots:

void connected();

void disconnected();

void bytesWritten(qint64 bytes);

void readyRead();

 

private:

QTcpSocket *socket;

 

};

 

#endif // MYTCPSOCKET_H

 

 

Once header file is done, let's move on to implementation file, mytcpsocket.cpp:

// mytcpsocket.cpp

 

#include "mytcpsocket.h"

 

MyTcpSocket::MyTcpSocket(QObject *parent) :

QObject(parent)

{

}

 

void MyTcpSocket::doConnect()

{

socket = new QTcpSocket(this);

 

connect(socket, SIGNAL(connected()),this, SLOT(connected()));

connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));

connect(socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));

connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));

 

qDebug() << "connecting...";

 

// this is not blocking call

socket->connectToHost("google.com", 80);

 

// we need to wait...

if(!socket->waitForConnected(5000))

{

qDebug() << "Error: " << socket->errorString();

}

}

 

void MyTcpSocket::connected()

{

qDebug() << "connected...";

 

// Hey server, tell me about you.

socket->write("HEAD / HTTP/1.0\r\n\r\n\r\n\r\n");

}

 

void MyTcpSocket::disconnected()

{

qDebug() << "disconnected...";

}

 

void MyTcpSocket::bytesWritten(qint64 bytes)

{

qDebug() << bytes << " bytes written...";

}

 

void MyTcpSocket::readyRead()

{

qDebug() << "reading...";

 

// read the data from the socket

qDebug() << socket->readAll();

}

 

 

The void QAbstractSocket::connectToHost(const QString & hostName, quint16 port, OpenMode openMode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol) function attempts to make a connection to hostName on the given port. The protocol parameter can be used to specify which network protocol to use (eg. IPv4 or IPv6).

 

The socket is opened in the given openMode and first enters HostLookupState, then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters ConnectedState and emits connected().

 

At any point, the socket can emit error() to signal that an error occurred.

 

The hostName may be an IP address in string form (e.g., "43.195.83.32"), or it may be a host name (e.g., "example.com"). QAbstractSocket will do a lookup only if required. port is in native byte order.

 

The bool QAbstractSocket::waitForConnected(int msecs = 30000) waits until the socket is connected, up to msecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, we can call error() to determine the cause of the error.

 

For buffered devices, the bool QIODevice::waitForBytesWritten(int msecs) function waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed. If msecs is -1, this function will not time out. For unbuffered devices, it returns immediately.

 

It returns true if a payload of data was written to the device; otherwise returns false (i.e. if the operation timed out, or if an error occurred).

 

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

 

The bool QAbstractSocket::waitForReadyRead(int msecs = 30000) is reimplemented from QIODevice::waitForReadyRead().

 

This function blocks until new data is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds.

 

The function returns true if the readyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out).

 

The qint64 QAbstractSocket::bytesAvailable() const is reimplemented from QIODevice::bytesAvailable().

 

This function eturns the number of incoming bytes that are waiting to be read.

 

The QByteArray QIODevice::readAll() reads all available data from the device, and returns it as a QByteArray.

 

 

 

Run the code, then we get:

connecting...

connected...

23 bytes written...

reading...

"HTTP/1.0 200 OK

Date: Wed, 18 Sep 2013 16:30:03 GMT

Expires: -1

Cache-Control: private, max-age=0

Content-Type: text/html; charset=ISO-8859-1

Set-Cookie: PREF=ID=c90a5b4f9f1a49f2:FF=0:TM=1379521803:LM=1379521803:S=uB_DHUgs

cgGzryP6; expires=Fri, 18-Sep-2015 16:30:03 GMT; path=/; domain=.google.com

Set-Cookie: NID=67=Ms_cR4zdNEnW3NUkq9oE3nHt7pyMAsQ4HHA1vKpbehn1xDHXUnMao7XUwsue0

xLOvqEyFU3zgGhH1l1ECVzyBcJzyHVzPVI5Z4FBD3cCEwmpFrHqDfF_4Rlr0s4yfOLP; expires=Thu

, 20-Mar-2014 16:30:03 GMT; path=/; domain=.google.com; HttpOnly

P3P: CP="This is not a P3P policy! See //www.google.com/support/accounts/bi

n/answer.py?hl=en&answer=151657 for more info."

Server: gws

X-XSS-Protection: 1; mode=block

X-Frame-Options: SAMEORIGIN

Alternate-Protocol: 80:quic

 

"

disconnected...

 

 

Here are the files used in this tutorial.

 

We can get it from TcpSocket.zip.

 

 

main.cpp:

#include

#include "mytcpsocket.h"

 

int main(int argc, char *argv[])

{

QCoreApplication a(argc, argv);

 

MyTcpSocket s;

s.doConnect();

 

return a.exec();

}

 

 

 

mytcpsocket.h:

#ifndef MYTCPSOCKET_H

#define MYTCPSOCKET_H

 

#include

#include

#include

#include

 

class MyTcpSocket : public QObject

{

Q_OBJECT

public:

explicit MyTcpSocket(QObject *parent = 0);

 

void doConnect();

 

signals:

 

public slots:

void connected();

void disconnected();

void bytesWritten(qint64 bytes);

void readyRead();

 

private:

QTcpSocket *socket;

 

};

 

#endif // MYTCPSOCKET_H

 

 

 

 

mytcpsocket.cpp:

#include "mytcpsocket.h"

 

MyTcpSocket::MyTcpSocket(QObject *parent) :

QObject(parent)

{

}

 

void MyTcpSocket::doConnect()

{

socket = new QTcpSocket(this);

 

connect(socket, SIGNAL(connected()),this, SLOT(connected()));

connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));

connect(socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));

connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));

 

qDebug() << "connecting...";

 

// this is not blocking call

socket->connectToHost("google.com", 80);

 

// we need to wait...

if(!socket->waitForConnected(5000))

{

qDebug() << "Error: " << socket->errorString();

}

}

 

void MyTcpSocket::connected()

{

qDebug() << "connected...";

 

// Hey server, tell me about you.

socket->write("HEAD / HTTP/1.0\r\n\r\n\r\n\r\n");

}

 

void MyTcpSocket::disconnected()

{

qDebug() << "disconnected...";

}

 

void MyTcpSocket::bytesWritten(qint64 bytes)

{

qDebug() << bytes << " bytes written...";

}

 

void MyTcpSocket::readyRead()

{

qDebug() << "reading...";

 

// read the data from the socket

qDebug() << socket->readAll();

}

 

 

 

 

 

 

 

 

Qt 5 Tutorial

1.Hello World

2.Signals and Slots

3.Q_OBJECT Macro

4.MainWindow and Action

5.MainWindow and ImageViewer using Designer A

6.MainWindow and ImageViewer using Designer B

7.Layouts

8.Layouts without Designer

9.Grid Layouts

10.Splitter

11.QDir

12.QFile (Basic)

13.Resource Files (.qrc)

14.QComboBox

15.QListWidget

16.QTreeWidget

17.QAction and Icon Resources

18.QStatusBar

19.QMessageBox

20.QTimer

21.QList

22.QListIterator

23.QMutableListIterator

24.QLinkedList

25.QMap

26.QHash

27.QStringList

28.QTextStream

29.QMimeType and QMimeDatabase

30.QFile (Serialization I)

31.QFile (Serialization II - Class)

32.Tool Tips in HTML Style and with Resource Images

33.QPainter

34.QBrush and QRect

35.QPainterPath and QPolygon

36.QPen and Cap Style

37.QBrush and QGradient

38.QPainter and Transformations

39.QGraphicsView and QGraphicsScene

40.Customizing Items by inheriting QGraphicsItem

41.QGraphicsView Animation

42.FFmpeg Converter using QProcess

43.QProgress Dialog - Modal and Modeless

44.QVariant and QMetaType

45.QtXML - Writing to a file

46.QtXML - QtXML DOM Reading

47.QThreads - Introduction

48.QThreads - Creating Threads

49.Creating QThreads using QtConcurrent

50.QThreads - Priority

51.QThreads - QMutex

52.QThreads - GuiThread

53.QtConcurrent QProgressDialog with QFutureWatcher

54.QSemaphores - Producer and Consumer

55.QThreads - wait()

56.MVC - ModelView with QListView and QStringListModel

57.MVC - ModelView with QTreeView and QDirModel

58.MVC - ModelView with QTreeView and QFileSystemModel

59.MVC - ModelView with QTableView and QItemDelegate

60.QHttp - Downloading Files

61.QNetworkAccessManager and QNetworkRequest - Downloading Files

62.Qt's Network Download Example - Reconstructed

63.QNetworkAccessManager - Downloading Files with UI and QProgressDialog

64.QUdpSocket

65.QTcpSocket

66.QTcpSocket with Signals and Slots

67.QTcpServer - Client and Server

68.QTcpServer - Loopback Dialog

69.QTcpServer - Client and Server using MultiThreading

70.QTcpServer - Client and Server using QThreadPool

71.Asynchronous QTcpServer - Client and Server using QThreadPool

72.Qt Quick2 QML Animation - A

73.Qt Quick2 QML Animation - B

74.Short note on Ubuntu Install

75.OpenGL with QT5

76.Qt5 Webkit : Web Browser with QtCreator using QWebView Part A

77.Qt5 Webkit : Web Browser with QtCreator using QWebView Part B

78.Video Player with HTML5 QWebView and FFmpeg Converter

79.Qt5 Add-in and Visual Studio 2012

80.Qt5.3 Installation on Ubuntu 14.04

81.Qt5.5 Installation on Ubuntu 14.04

82.Short note on deploying to Windows




Qt 5 Tutorial

  1. Hello World
  2. Signals and Slots
  3. Q_OBJECT Macro
  4. MainWindow and Action
  5. MainWindow and ImageViewer using Designer A
  6. MainWindow and ImageViewer using Designer B
  7. Layouts
  8. Layouts without Designer
  9. Grid Layouts
  10. Splitter
  11. QDir
  12. QFile (Basic)
  13. Resource Files (.qrc)
  14. QComboBox
  15. QListWidget
  16. QTreeWidget
  17. QAction and Icon Resources
  18. QStatusBar
  19. QMessageBox
  20. QTimer
  21. QList
  22. QListIterator
  23. QMutableListIterator
  24. QLinkedList
  25. QMap
  26. QHash
  27. QStringList
  28. QTextStream
  29. QMimeType and QMimeDatabase
  30. QFile (Serialization I)
  31. QFile (Serialization II - Class)
  32. Tool Tips in HTML Style and with Resource Images
  33. QPainter
  34. QBrush and QRect
  35. QPainterPath and QPolygon
  36. QPen and Cap Style
  37. QBrush and QGradient
  38. QPainter and Transformations
  39. QGraphicsView and QGraphicsScene
  40. Customizing Items by inheriting QGraphicsItem
  41. QGraphicsView Animation
  42. FFmpeg Converter using QProcess
  43. QProgress Dialog - Modal and Modeless
  44. QVariant and QMetaType
  45. QtXML - Writing to a file
  46. QtXML - QtXML DOM Reading
  47. QThreads - Introduction
  48. QThreads - Creating Threads
  49. Creating QThreads using QtConcurrent
  50. QThreads - Priority
  51. QThreads - QMutex
  52. QThreads - GuiThread
  53. QtConcurrent QProgressDialog with QFutureWatcher
  54. QSemaphores - Producer and Consumer
  55. QThreads - wait()
  56. MVC - ModelView with QListView and QStringListModel
  57. MVC - ModelView with QTreeView and QDirModel
  58. MVC - ModelView with QTreeView and QFileSystemModel
  59. MVC - ModelView with QTableView and QItemDelegate
  60. QHttp - Downloading Files
  61. QNetworkAccessManager and QNetworkRequest - Downloading Files
  62. Qt's Network Download Example - Reconstructed
  63. QNetworkAccessManager - Downloading Files with UI and QProgressDialog
  64. QUdpSocket
  65. QTcpSocket
  66. QTcpSocket with Signals and Slots
  67. QTcpServer - Client and Server
  68. QTcpServer - Loopback Dialog
  69. QTcpServer - Client and Server using MultiThreading
  70. QTcpServer - Client and Server using QThreadPool
  71. Asynchronous QTcpServer - Client and Server using QThreadPool
  72. Qt Quick2 QML Animation - A
  73. Qt Quick2 QML Animation - B
  74. Short note on Ubuntu Install
  75. OpenGL with QT5
  76. Qt5 Webkit : Web Browser with QtCreator using QWebView Part A
  77. Qt5 Webkit : Web Browser with QtCreator using QWebView Part B
  78. Video Player with HTML5 QWebView and FFmpeg Converter
  79. Qt5 Add-in and Visual Studio 2012
  80. Qt5.3 Installation on Ubuntu 14.04
  81. Qt5.5 Installation on Ubuntu 14.04
  82. Short note on deploying to Windows

 

반응형
Comments