👉 버튼 클릭시 다이얼로그 창과 새로운 창을 오픈합니다.
When you click the button, a dialog window and a new window open.
👉 새로운 창에서 텍스트 입력하고 버튼 클릭시 mainwindow의 라벨에 텍스트가 출력됩니다.
Enter text in a new window and click the button to display the text in the label of the mainwindow.
👉 새로운창과 이전 창 사이의 변수 전달은 시그널과 슬롯을 사용합니다.
Passing variables between new and old windows uses signals and slots.
1.클래스 및 폼 추가 / Add classes and forms


2.폼디자인 / Form Deisgn
✔️ 좌측은 dialog.ui 오른쪽은 mainwinodw.ui
On the left is dialog.ui and on the right is mainwinodw.ui


3.Header Files
✔️ Dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
// 암시적 형변환방지,실수 방지용
// To prevent implicit type conversion and mistakes
explicit Dialog(QWidget *parent = nullptr);
// 소멸자:객체 삭제시 호출
// Destructor: Called when the object is deleted
~Dialog();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
✔️ mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
// 새창 열기 슬롯
// Open new window slot
void openNewWindow();
// Label출력 슬롯
// Label output slot
void updateLabel(const QString text);
// Dialog슬롯
// Dialog slot
void openDialog();
};
#endif // MAINWINDOW_H
✔️ newwindow.h
#ifndef NEWWINDOW_H
#define NEWWINDOW_H
// <QWidget의 헤더파일을 포함
#include <QWidget>
// 전방 선언(forward declaration)
// class <className> 이런 형식만 있는 경우 전방 선언이라고합니다.
// QLineEdit과 QPushButton을 포인터로만 사용할 경우, 전체 헤더를 포함하지 않아도 됩니다.
// 이렇게 하면 컴파일 속도가 빨라지고, 의존성이 줄어듭니다.
// Forward declaration
// If the format is only class <className>, it is called a forward declaration.
// If you only use QLineEdit and QPushButton as pointers, you don't need to include the entire header.
// This speeds up compilation and reduces dependencies.
class QLineEdit;
class QPushButton;
class NewWindow : public QWidget
{
// 매크로 / macro
Q_OBJECT
public:
// 암시적 형변환 금지 : 실수 방지, 코드 명확성, 안전한 생성자 호출
// 암시적 형변환이란 QT자체에서 파라메터로 대입되는 값을 자동으로 추정하는 기능
// Implicit type conversions are prohibited: Preventing mistakes, improving code clarity, and ensuring safe constructor calls.
// Implicit type conversion is a feature of QT itself that automatically infers the values assigned to parameters.
explicit NewWindow(QWidget *parent = nullptr);
signals:
// 메인창으로 보낼 시그널
// Signal to send to the main window
void textSubmitted(const QString &text);
private:
QLineEdit* inputField;
QPushButton* confirmButton;
};
#endif // NEWWINDOW_H
4. Source FIles
✔️ dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
}
// 소멸자
// destructor
Dialog::~Dialog()
{
delete ui;
}
✔️ main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
// -- 코드 수정 없음 / No code modification --
✔️ mainwindow.cpp
#include "mainwindow.h"
#include "./ui_mainwindow.h"
// 새 창 클래스 포함 / Include a new window class
#include "newwindow.h"
// dialog 클래스 포함 / Includes dialog class
#include "dialog.h"
// cout과 유사한 디버깅 클래스 / Debugging class similar to cout
#include <QDebug>
// 자바스크립트 alert과 유사한 디버깅 클래스
// A debugging class similar to JavaScript Alert
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 버튼 클릭 시 새 창 열기
// Open a new window when the button is clicked
connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::openNewWindow);
// 버튼 클릭시 다이얼로그 띄우기
// Pop up a dialog when a button is clicked
connect(ui->pushButton_2, &QPushButton::clicked, this, &MainWindow::openDialog);
}
// 새창 띄우는 슬롯 함수
// Slot function to open a new window
void MainWindow::openNewWindow(){
// === 디버깅 / Debugging ===
qDebug() << "openNewWindow 슬롯 실행됨/slot executed!";
//QMessageBox::information(this, "테스트/test", "슬롯이 실행되었습니다/The slot has been run.!");
// 부모 없이 독립 창(디버깅)
// Independent window without parent (debugging)
//NewWindow* window = new NewWindow(nullptr);
NewWindow* window = new NewWindow(this);
// 독립된 창으로 설정
// Set as independent window
window->setWindowFlags(Qt::Window);
// 시그널과 슬롯 연결(라벨 출력용)
// Connecting signals and slots (for label output)
connect(window, &NewWindow::textSubmitted, this, &MainWindow::updateLabel);
// 닫을 때 메모리 자동 해제
// Automatically free memory when closing
window->setAttribute(Qt::WA_DeleteOnClose);
window->show();
}
// MainWindow의 라벨에 텍스트 출력하는 슬롯 함수
// Slot function that outputs text to the label of MainWindow
// newwindow.cpp에서 시그널 발생
// Signal generated in newwindow.cpp
void MainWindow::updateLabel(const QString text){
// 라벨에 텍스트 출력
// Print text to label
ui->label->setText(text);
}
// 다이얼로그 창 띄우는 슬롯 함수
// Slot function to open a dialog window
void MainWindow::openDialog()
{
Dialog* dialog = new Dialog(this);
// 다이얼로그 창으로 설정
// Set to dialog window
dialog->setWindowFlags(Qt::Dialog);
// 닫을때 메모리해제
// Free memory when closing
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
// 소멸자 / destructor
// 객체가 삭제되거나 범위를 벗어날 때 자동으로 호출되는 함수입니다.
// A function that is automatically called when an object is deleted or goes out of scope.
MainWindow::~MainWindow()
{
delete ui;
}
.✔️ newwindow.cpp
#include "newwindow.h"
#include <QVBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QDebug>
NewWindow::NewWindow(QWidget *parent) : QWidget(parent)
{
setWindowTitle("new window");
resize(400,300);
// ui추가,ui디자인 파일 없는 경우.
// Add UI, if there is no UI design file.
inputField = new QLineEdit(this);
confirmButton = new QPushButton("확인/Confirm",this);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(inputField);
layout->addWidget(confirmButton);
//&QPushButton::clicked 이 시그널 발생시 [this]()슬롯 함수 실행
//&QPushButton::clicked When this signal occurs, the [this]() slot function is executed.
connect(confirmButton, &QPushButton::clicked, this, [this](){
QString text = inputField->text();
emit textSubmitted(text); // 시그널 발생
qDebug() << "입력된 테스트/Enterd TExt:" << text;
//close();// 창닫기 / Close window
});
}
5.실행 / Run
