사용자 도구

사이트 도구


qt:helloworld

"Hello, World!" in Qt

Qt를 아래처럼 시그널과 슬롯을 이용해 “Hello, World!”를 아주 객체지향적(?)으로 출력할 수 있다. 그냥 “Hello, World!”를 출력하는 것보다는 한참 복잡하지만, Qt의 시그널, 슬롯 매커니즘이 잘 노출되어 있으므로 Qt 시작에 있어 개념을 잘 보여주는 예제라고도 볼 수 있다.

main.cpp
#include <QCoreApplication>
#include <QTimer>
#include "signal_emitter.h"
 
int main(int argc, char *argv[])
{
  QCoreApplication app(argc, argv);
 
  // emitter is now a child of core application app.
  // app will delete emitter.
  signal_emitter *emitter = new signal_emitter(&app);
 
  // when emitter emits 'finished' signal, app will be terminated.
  QObject::connect(emitter, SIGNAL(finished()), &app, SLOT(quit()));
 
  // we emit initial 'launch()'.
  QTimer::singleShot(0, emitter, SLOT(launch()));
 
  return app.exec();
}

실제로 작업을 담당하는 signal_emitter 클래스는 다음과 같이 정의하였다.

signal_emitter.h
#ifndef SIGNAL_EMITTER_H
#define SIGNAL_EMITTER_H
 
#include <QObject>
 
class signal_emitter : public QObject
{
  Q_OBJECT
public:
  explicit signal_emitter(QObject *parent = 0);
 
signals:
  void finished(); // DO NOT implement, or will cause link error.
 
public slots:
  void launch(); // Fired by QTimer::singleShot()
};
 
#endif // SIGNAL_EMITTER_H
signal_emitter.cpp
#include "signal_emitter.h"
#include <iostream>
 
signal_emitter::signal_emitter(QObject *parent) :
  QObject(parent)
{
}
 
void signal_emitter::launch()
{
  std::cout << "Hello, world!\n";
 
  emit finished();
}

소스 코드는 여기서 다운로드 가능하다. 시그널과 슬롯에 대해서는 SignalsAndSlots에서 보다 자세히 다룰 것이다.

qt/helloworld.txt · 마지막으로 수정됨: 2014/10/09 21:24 저자 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki