지금까지는 모든 코드를 main 함수에 넣었습니다.
간단한 예제에서는 문제가되지 않았지만 점점 더 복잡한 응용 프로그램에서는 코드를 다른 클래스로 분할 할 수 있습니다. 자주 수행되는 작업은 창을 표시하는 데 사용되는 클래스를 작성하고 이 창에 포함 된 모든 위젯을 이 클래스의 속성으로 구현하는 것입니다.
project -> AddNew
을 선택, 새클래스를 만들어보자.
클래스 이름을 적고 ,, base class는 QWidget 선택.
소스파일과 헤더파일이 생성됬을 것이다.
헤더파일
소스파일
window::window(QWidget *parent) : QWidget(parent){ // ->window 생성자
}
window 구현은 생성자에서 수행됩니다. window의 크기와 이 window의 포함 위젯 및 위치를 선언 할 수 있습니다. 예를 들어, 버튼이 포함 된 창을 구현하는 방법은 다음과 같습니다.
main.cpp
#include <QApplication>
#include "window.h"
int main(int argc, char **argv)
{
QApplication app (argc, argv);
Window window;
window.show();
return app.exec();
}
window.h
#ifndef WINDOW_H
#define WINDOW_H
#include <QWidget>
#include <QPushButton>
class QPushButton;
class Window : public QWidget
{
public:
explicit Window(QWidget *parent = 0);
private:
QPushButton *m_button; // 버튼 생성
};
#endif // WINDOW_H
window.cpp
#include "window.h"
Window::Window(QWidget *parent) :
QWidget(parent)
{
// Set size of the window
setFixedSize(100, 50);
// Create and position the button
m_button = new QPushButton("Hello World", this);
m_button->setGeometry(10, 10, 80, 30);
}
m_button을 삭제하기 위해 소멸자(destructor)를 작성할 필요가 없습니다. parenting system을 사용하면 Window 인스턴스가 스택을 벗어나면 m_button이 자동으로 삭제됩니다.
'qt 사용하기' 카테고리의 다른 글
Parenting system (0) | 2019.12.19 |
---|---|
Qt class hierarchy (0) | 2019.12.19 |
A pretty button- 버튼 꾸미기 (0) | 2019.12.19 |
Qt 프로그램 컴파일 방법-qmake (0) | 2019.12.19 |
qt 모듈 (0) | 2019.12.19 |
댓글