티스토리 뷰

다음은 간단한 GUI 애플리케이션, Signal and Slots을 이용한 이벤트 처리, 파일 I/O 처리를 다루는 Qt의 몇 가지 기본 에제다. 이 예제에서는 기본적인 GUI 요소 처리부터 파일 입출력 수행, 대화창 생성에 이르기까지 필수적인 Qt 기능을 다룬다. Qt의 우연셩과 방대한 문서는 여러 플랫폼에서 복잡한 애플리케이션 개발을 위한 훌륭한 프레임워크다.

 

  1. Simpel GUI Application with a Button and Label
    : 이 예제에서는 버튼과 레이블이 있는 GUI 애플리케이션을 만든다. 버튼을 클릭하면 레이블 텍스트가 변경된다. 이 예제에서는 버튼의 clicked signal를 버튼 클릭 시 레이블 텍스트를 변경하는 사용자 지정 slot인 onButtonClicked에 연결한다.
    #include <QApplication>
    #include <QWidget>
    #include <QPushButton>
    #include <QLabel>
    #include <QVBoxLayout>
    
    class MainWindow : public QWidget
    {
        Q_OBJECT
    
    public:
        MainWindow()
        {
            auto* layout = new QVBoxLayout(this);
    
            label = new QLabel("Hello, Qt!", this);
            layout->addWidget(label);
    
            auto* button = new QPushButton("Click Me", this);
            layout->addWidget(button);
    
            connect(button, &QPushButton::clicked, this, &MainWindow::onButtonClicked);
        }
    
    private slots:
        void onButtonClicked()
        {
            label->setText("Button clicked!");
        }
    
    private:
        QLabel* label;
    };
    
    int main(int argc, char* argv[])
    {
        QApplication app(argc, argv);
        MainWindow window;
        window.show();
        return app.exec();
    }


  2. Signals and Slots Example with a Slider and Progress Bar
    : 이 예제에는 Qt의 Signals and Slots 시스템을 보여준다. 슬라이더를 진행률 표시줄에 연결해 슬라이더를 움직이면 진행률 표시줄 값이 업데이트 되도록 했다. 슬라이더의 valueChanged 신호가 진행률 표시줄의 setValue 슬롯에 직접 연결되어 있으므로 슬라이더를 움직이면 진행률 표시줄이 자동으로 업데이트 된다.
    #include <QApplication>
    #include <QWidget>
    #include <QSlider>
    #include <QProgressBar>
    #include <QVBoxLayout>
    
    class SliderWindow : public QWidget
    {
    public:
        SliderWindow()
        {
            auto* layout = new QVBoxLayout(this);
    
            slider = new QSlider(Qt::Horizontal, this);
            slider->setRange(0, 100);
            layout->addWidget(slider);
    
            progressBar = new QProgressBar(this);
            progressBar->setRange(0, 100);
            layout->addWidget(progressBar);
    
            // Connect slider value to progress bar
            connect(slider, &QSlider::valueChanged, progressBar, &QProgressBar::setValue);
        }
    
    private:
        QSlider* slider;
        QProgressBar* progressBar;
    };
    
    int main(int argc, char* argv[])
    {
        QApplication app(argc, argv);
        SliderWindow window;
        window.show();
        return app.exec();
    }


  3. Basic File I/O Example with a Text Edit and Save Button
    : 이 예제에서는 Qt에서 파일 입출력을 사용하는 방법을 보여준다. 사용자가 텍스트를 작성하고 파일에 저장할 수 있는 텍스트 편집기 애플리케이션을 생성한다. 이 예제에서는 사용자에게 파일 이름을 선택하라는 메시지를 표시하기 위해 QFileDialog 를 사용한다. 쓰기 위해 파일을 열 수 있으면 QTextEdit 에서 QTextStream 을 사용해 텍스트 파일에 쓴다. 오류가 발생하면 QMessageBox 에 경고가 표시된다.
    #include <QApplication>
    #include <QWidget>
    #include <QTextEdit>
    #include <QPushButton>
    #include <QVBoxLayout>
    #include <QFile>
    #include <QTextStream>
    #include <QFileDialog>
    #include <QMessageBox>
    
    class TextEditor : public QWidget
    {
        Q_OBJECT
    
    public:
        TextEditor()
        {
            auto* layout = new QVBoxLayout(this);
    
            textEdit = new QTextEdit(this);
            layout->addWidget(textEdit);
    
            auto* saveButton = new QPushButton("Save", this);
            layout->addWidget(saveButton);
    
            connect(saveButton, &QPushButton::clicked, this, &TextEditor::saveToFile);
        }
    
    private slots:
        void saveToFile()
        {
            QString fileName = QFileDialog::getSaveFileName(this, "Save File", "", "Text Files (*.txt)");
            if (fileName.isEmpty()) return;
    
            QFile file(fileName);
            if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
            {
                QMessageBox::warning(this, "Error", "Cannot save file: " + file.errorString());
                return;
            }
    
            QTextStream out(&file);
            out << textEdit->toPlainText();
            file.close();
        }
    
    private:
        QTextEdit* textEdit;
    };
    
    int main(int argc, char* argv[])
    {
        QApplication app(argc, argv);
        TextEditor editor;
        editor.show();
        return app.exec();
    }


  4. Basic Timer Example with QTimer
    : 이 예는 QTimer 를 사용해 주기적으로 이벤트를 트리거하고 경과된 초에 따라 레이블을 업데이트하는 방법을 보여준다. 이 예에서는 QTimer가 updateTime 슬롯에 연결돼 경과 시간 카운터를 증가시키고 초마다 레이블을 업데이트 한다.
    #include <QApplication>
    #include <QWidget>
    #include <QLabel>
    #include <QTimer>
    #include <QVBoxLayout>
    
    class TimerWindow : public QWidget
    {
        Q_OBJECT
    
    public:
        TimerWindow()
        {
            auto* layout = new QVBoxLayout(this);
    
            timerLabel = new QLabel("0 seconds", this);
            layout->addWidget(timerLabel);
    
            timer = new QTimer(this);
            connect(timer, &QTimer::timeout, this, &TimerWindow::updateTime);
            timer->start(1000); // Trigger every second
    
            elapsedSeconds = 0;
        }
    
    private slots:
        void updateTime()
        {
            elapsedSeconds++;
            timerLabel->setText(QString::number(elapsedSeconds) + " seconds");
        }
    
    private:
        QLabel* timerLabel;
        QTimer* timer;
        int elapsedSeconds;
    };
    
    int main(int argc, char* argv[])
    {
        QApplication app(argc, argv);
        TimerWindow window;
        window.show();
        return app.exec();
    }


  5. Creating a Dialog Window
    : 이 예제는 Qt에서 대화창을 생성하고 표시하는 방법을 보여준다. 여기서 "Show Dialog" 버튼을 클릭하면 QMessageBox::information 을 사용해 메시지 대화 상자를 표시하는 showMessage 슬롯이 트리거된다.
    #include <QApplication>
    #include <QWidget>
    #include <QPushButton>
    #include <QMessageBox>
    #include <QVBoxLayout>
    
    class DialogWindow : public QWidget
    {
        Q_OBJECT
    
    public:
        DialogWindow()
        {
            auto* layout = new QVBoxLayout(this);
    
            auto* showDialogButton = new QPushButton("Show Dialog", this);
            layout->addWidget(showDialogButton);
    
            connect(showDialogButton, &QPushButton::clicked, this, &DialogWindow::showMessage);
        }
    
    private slots:
        void showMessage()
        {
            QMessageBox::information(this, "Dialog", "Hello from the dialog!");
        }
    };
    
    int main(int argc, char* argv[])
    {
        QApplication app(argc, argv);
        DialogWindow window;
        window.show();
        return app.exec();
    }


 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함
반응형