2015. 8. 23. 20:12

Using a Designer UI File in Your Application

Using a Designer UI File in Your Application

당신의 응용프로그램에 있는 디자이너 UI 파일을 사용하기

출처 : http://doc.qt.io/qt-5/designer-using-a-ui-file.html

Qt Designer UI files represent the widget tree of the form in XML format. The forms can be processed:

Qt 디자이너 UI 파일은 위젯 트리 구조를 XML 형식으로 보여주고 있습니다. 폼(양식) 은 다음의 시점에서 처리가 될 수 있습니다.

  • At compile time, which means that forms are converted to C++ code that can be compiled.
  • 컴파일 시기, 이는 컴파일이 되는 C++ 코드로 폼이 변경된다는 것을 의미합니다.
  • At runtime, which means that forms are processed by the QUiLoader class that dynamically constructs the widget tree while parsing the XML file.
  • 실행 중 (런타임), 이는 XML 파일을 읽어서 위젯 트리를 생성하는 QUiLoader 클래스 에 의해 처리된다는 것을 의미합니다.

Compile Time Form Processing

컴파일 시기 폼 처리

You create user interface components with Qt Designer and use Qt's integrated build tools, qmake and uic, to generate code for them when the application is built. The generated code contains the form's user interface object. It is a C++ struct that contains:

사용자는 Qt 디자이너와 의 내장된 빌드 도구인 qmake 와 uic 를 사용하여 응용프로그램이 빌드 될때 사용자 인터페이스 컴포넌트들을 만듭니다.

  • Pointers to the form's widgets, layouts, layout items, button groups, and actions.
  • 폼의 위젯, 레이아웃, 레이아웃 아이템, 버튼 그룹과 액션을 가리키는 포인터들
  • A member function called setupUi() to build the widget tree on the parent widget.
  • 부모 위젯 상에 위젯 트리를 생성하는 setupUi() 맴버 함수
  • A member function called retranslateUi() that handles the translation of the string properties of the form. For more information, see Reacting to Language Changes.
  • 폼의 문자열 속성을 번역하는 것을 처리하는 retranslateUi() 라는 맴버 함수. 자세한 정보를 위해서는 언어 변화에 대응하기를 참고 바랍니다.

The generated code can be included in your application and used directly from it. Alternatively, you can use it to extend subclasses of standard widgets.

생성된 코드는 응용프로그램 내에 포함되고, 직접 사용할 수있습니다. 그렇게 하는 대신, 당신은 표준 위젯의 서브 클래스들을 확장하는 용도로도 쓸 수 있습니다.

A compile time processed form can be used in your application with one of the following approaches:

컴파일 시기에 처리된 폼은 다음의 접근 방침들 중 하나를 써서 응용프로그램에서 사용될 수 있습니다.

  • The Direct Approach: you construct a widget to use as a placeholder for the component, and set up the user interface inside it.
  • 직접 접근 : 당신은 컴포넌트를 위한 지지대로 위젯을 생성하고, 그 안에 사용자 인터페이스를 설정합니다.
  • The Single Inheritance Approach: you subclass the form's base class (QWidget or QDialog, for example), and include a private instance of the form's user interface object.
  • 단일 상속 접근 : 부모 클래스를 상속(서브클래스 생성) 하고(예를 들어, QWidget 또는 QDialog), 폼의 사용자 인터페이스 객체의 프라이빗 인스턴스를 포함합니다.
  • The Multiple Inheritance Approach: you subclass both the form's base class and the form's user interface object. This allows the widgets defined in the form to be used directly from within the scope of the subclass.
  • 다중 상속 접근 : 폼의 부모 클래스와 사용자 인터페이스 객체를 동시에 상속합니다. 이는 위젯들이 서브 클래스의 범위 내에서 사용되는 폼을 정의할 수 있게 합니다.

To demonstrate, we create a simple Calculator Form application. It is based on the original Calculator Form example.

이를 보여 주기 위해, 우리는 Calculator Form (계산기 폼/양식) 를 생성합니다. 이는 원래의 계산기 폼 예제를 기반으로 합니다.

The application consists of one source file, main.cpp and a UI file.

이 응용프로그램은 하나의 소스 파일인 main.cpp 와 UI 파일로 구성되어 있습니다.

The calculatorform.ui file designed with Qt Designer is shown below:

Qt 디자이너에 의해 아래와 같이 디자인 되어 있습니다.

We will use qmake to build the executable, so we need to write a .pro file:

우리는 실행 프로그램을 만드는데, qmake 를 사용할 것이기에 .pro 파일을 만들 필요가 있습니다.

HEADERS     = calculatorform.h

The special feature of this file is the FORMS declaration that tells qmake which files to process with uic. In this case, the calculatorform.ui file is used to create a ui_calculatorform.h file that can be used by any file listed in the SOURCES declaration.

이 파일내에 특별한 기능으로 FORMS 선언이 잇는데, 이는 qmake 에게 uic 를 사용해서 처리할 파일들을 알려 줍니다. 이 경우, SOURCES 선언에 등록된 어떠한 파일에서도 사용될 수 있는 ui_calculatorform.h 을 만드는 데 사용하는 calculatorform.ui 파일을 이용합니다.

Note: You can use Qt Creator to create the Calculator Form project. It automatically generates the main.cpp, UI, and .pro files, which you can then modify.

참고: 당신은 Calculator Form 프로젝트를 만들기 위해서 Qt 크리에이터를 사용할 수 있습니다. 이 프로그램은 사용자가 변경 할 수 있는 main.cpp, UI, 그리고 .pro 파일을 자동으로 생성해줍니다.

The Direct Approach

직접 접근

To use the direct approach, we include the ui_calculatorform.h file directly in main.cpp:

직접 접근 방법을 사용하기 위해, 우리는 main.cpp 내에 ui_calculatorform.h 파일을 직접 포함(include) 시킵니다.

#include "ui_calculatorform.h"

The main function creates the calculator widget by constructing a standard QWidget that we use to host the user interface described by the calculatorform.ui file.

calculatorform.ui 파일에 의해 설명(기술)된 사용자 인터페이스 설정을 다루는 표준 QWidget 을 생성하는 방법으로 main 함수가 위젯을 계산기 위젯을 생성합니다.

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWidget *widget = new QWidget;
    Ui::CalculatorForm ui;
    ui.setupUi(widget);

    widget->show();
    return app.exec();
}

In this case, the Ui::CalculatorForm is an interface description object from the ui_calculatorform.h file that sets up all the dialog's widgets and the connections between its signals and slots.

이 경우, UI::CalclualtorForm 은 대화창의 위젯과 (그와 관련된) 시그널과 슬롯을 설정하는 ui_calculatorform.h 파일에 있는 인터페이스 설명 객체(디스크립션 오브젝트) 입니다.

The direct approach provides a quick and easy way to use simple, self-contained components in your applications. However, components created with Qt Designer often require close integration with the rest of the application code. For instance, the CalculatorForm code provided above will compile and run, but the QSpinBox objects will not interact with the QLabel as we need a custom slot to carry out the add operation and display the result in the QLabel. To achieve this, we need to use the single inheritance approach.

직접 접근 방법은 사용자의 응용프로그램 내에 자립(독립) 되고, 단순한 방식으로 쉽고 빠릅니다. 하지만, Qt 디자이너를 사용해서 만든 컴포넌트들은 보통 응용 프로그램의 남은 부분과 결합하는데 밀접한 통합 작업을 요구합니다 (뒷처리). 예를 들어 위에 제공된 CalculatorForm 코드는 컴파일과 실행까지는 제공합니다. 하지만 QSpinBox 객체는 덧셈 계산을 하여 QLabel 형태로 결과 값을 표시하는데 사용되는 필요한 커스텀(사용자 맞춤 변경) 슬롯을 포함한 QLabel 이 아닙니다. 이를 해결 하기 위해, 우리는 단일 상속 접근을 사용할 필요가 있습니다.

The Single Inheritance Approach

단일 상속 접근

To use the single inheritance approach, we subclass a standard Qt widget and include a private instance of the form's user interface object. This can take the form of:

단일 상속 접근을 사용하기 위해, 우리는 표준 Qt 위젯을 상속하고, 폼의 사용자 인터페이스 객체의 프라이빗 인스턴스를 포함해야합니다. 이는 다음의 형태를 가질 수 있습니다.

  • A member variable
  • 하나의 맴버 변수
  • A pointer member variable
  • 하나의 포인터 맴버 변수

Using a Member Variable

하나의 맴버 변수 사용하기

In this approach, we subclass a Qt widget and set up the user interface from within the constructor. Components used in this way expose the widgets and layouts used in the form to the Qt widget subclass, and provide a standard system for making signal and slot connections between the user interface and other objects in your application. The generated Ui::CalculatorForm structure is a member of the class.

이 접근 방식에서 우리는 Qt 위젯을 상속하고 생성자 내에서 사용자 인터페이스 폼을 설정합니다. 이런 방법으로 컴포넌트들은 이 폼에서 사용되는 위젯과 레이어아웃이 Qt 위젯 서브클래스들에게  노출됩니다. 그리고 사용자의 응용프로그램에서 사용자 인터페이스와 다른 객체들간에 연결된 시그널과 슬롯을 위한 표준 시스템(방식)을 제공합니다. 생성된 Ui::CalculatorForm 구조는 클래스의 한 구성 요소 (맴버) 입니다.

This approach is used in the Calculator Form example.

이런 접근 방식이 계산기 양식 예제에 사용되었습니다.

To ensure that we can use the user interface, we need to include the header file that uic generates before referring to Ui::CalculatorForm:

해당 사용자 인터페이스를 사용할 수 있음을 확인하게 위해, 우리는 Ui::CalculatorForm 을 참조하기 전에, uic 가 생성한 헤더 파일을 포함시킬 필요가 있습니다.

#include "ui_calculatorform.h"

This means that the .pro file must be updated to include calculatorform.h:

이는 calculatorform.h 를 포함하기 위해서 .pro 파일을 갱신 시켜야 함을 의미합니다.

HEADERS     = calculatorform.h

The subclass is defined in the following way:

서브클래스(상속 받은 클래스) 는 다음의 방식으로 정의 됩니다.

class CalculatorForm : public QWidget
{
    Q_OBJECT

public:
    CalculatorForm(QWidget *parent = 0);

private slots:
    void on_inputSpinBox1_valueChanged(int value);
    void on_inputSpinBox2_valueChanged(int value);

private:
    Ui::CalculatorForm ui;
};

The important feature of the class is the private ui object which provides the code for setting up and managing the user interface.

이 클래스의 중요한 특징으로 프라이빗 (속성을 가진) ui 객체는 사용자 인터페이스를 설정과 관리르 위한 코드를 제공한다는 것입니다

The constructor for the subclass constructs and configures all the widgets and layouts for the dialog just by calling the ui object's setupUi() function. Once this has been done, it is possible to modify the user interface as needed.

서브 클래스를 위한 상속자는 단순히 ui 객체의 setupUi() 함수를 호출하는 방법으로 대화창을 위한 모든 위젯과 레이아웃을 설정합니다. 이 작업으 끝나면, 필요했던 사용자 인터페이스를 변경하는 것이 가능해집니다.

CalculatorForm::CalculatorForm(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
}

We can connect signals and slots in user interface widgets in the usual way by adding the on_<object name> - prefix. For more information, see widgets-and-dialogs-with-auto-connect.

우리는 on_<객체 이름> 접두어를 추가하는 방법으로 통상적인 사용자 인터페이스 내에 있는 시그널과 슬롯을 연결 할 수 있습니다. 자세한 정보가 필요하면, 자동 연결 방식으로 위젯과 대화창을 연결하기를 참고 바랍니다.

The advantages of this approach are its simple use of inheritance to provide a QWidget-based interface, and its encapsulation of the user interface widget variables within the ui data member. We can use this method to define a number of user interfaces within the same widget, each of which is contained within its own namespace, and overlay (or compose) them. This approach can be used to create individual tabs from existing forms, for example.

이 방식의 이점은, QWidget 기반 인터페이스와 ui 데이터 맴버 내에서 사용자 인터페이스 위젯 변수들의 캡슐화를 제공하기 위한 상속 작업의 단순성에 있습니다. 우리는 같은 위젯 내에서 자신만의 네임스페이스와 이들을 덮는(오버레이) (또는 조합하는) 정보를 포함하는 다수의 사용자 인터페이스를 정의하는데 사용할 수 있습니다. 예를 들면, 동일하게 존재하는 폼들에서 각각의 탭을 만드는 작업을 하는데 사용될 수 있습니다.

Using a Pointer Member Variable

하나의 포인터 맴버(구성원) 변수 사용하기

Alternatively, the Ui::CalculatorForm structure can be made a pointer member of the class. The header then looks as follows:

다른 방법으로, Ui::CalculatorForm 구조는 클래스의 포인터 맴버로 만들수 있습니다. 그러면, 헤더는 다음의 형태로 구성됩니다.

namespace Ui {
    class CalculatorForm;
}

class CalculatorForm : public QWidget
...
virtual ~CalculatorForm();
...
private:
    Ui::CalculatorForm *ui;
...

The corresponding source file looks as follows:

이에 대응되는 소스 파일은 다음과 같아집니다.

#include "ui_calculatorform.h"

CalculatorForm::CalculatorForm(QWidget *parent) :
    QWidget(parent), ui(new Ui::CalculatorForm)
{
    ui->setupUi(this);
}

CalculatorForm::~CalculatorForm()
{
    delete ui;
}

The advantage of this approach is that the user interface object can be forward-declared, which means that we do not have to include the generated ui_calculatorform.h file in the header. The form can then be changed without recompiling the dependent source files. This is particularly important if the class is subject to binary compatibility restrictions.

이런 접근 방법의 장점은 사용자 인터페이스 객체가 전방 선언될 수 있다는 것인데, 이 것은 생성된 ui_calculatorform.h 파일을 헤더 부분에 포함하지 않아도 된다는 것입니다. 폼은 의존된(폼의 변경에 의존하는) 소스 파일들을 재컴파일 하지 않고도 변경할 수 있습니다. 이것은 클래스가 바이너리 호환성 제한에 영향을 받는다면 특별히 중요합니다.

We generally recommend this approach for libraries and large applications. For more information, see Creating Shared Libraries.

우리는 라이브러리와 대규모 응용프로그램의 접근에 대해서 일반적으로 이런 접근 방법을 권장합니다. 자세한 정보는 공유 라이브러리 작성을 참고 바랍니다.

The Multiple Inheritance Approach

다중 상속 접근

Forms created with Qt Designer can be subclassed together with a standard QWidget-based class. This approach makes all the user interface components defined in the form directly accessible within the scope of the subclass, and enables signal and slot connections to be made in the usual way with the connect() function.

Qt 디자이너로 만들어진 폼들은 표준 QWidget-기반 클래스와 결합되어 상속될 수 있습니다. 이 접근 방법은 모든 사용자 인터페이스를 서브 클래스의 범위내에서 직접 접근 가능한 폼에서 정의 하게 하고, 평상시에 사용하는 connect() 함수를 사용하여 시그널과 슬롯 연결을 가능하게 합니다.

This approach is used in the Multiple Inheritance example.

이 접근 방법은 다중 상속 예제에서 사용됩니다.

We need to include the header file that uic generates from the calculatorform.ui file, as follows:

우리는 uic (User Interface Compiler) 가 calculatorform.ui 를 통해 만든 헤더 파일을 아래와 같은 방법으로 포함시킬 필요가 있습니다.

#include "ui_calculatorform.h"

The class is defined in a similar way to the one used in the single inheritance approach, except that this time we inherit from both QWidget and Ui::CalculatorForm, as follows:

아래와 같이, 클래스는 단일 상속 접근에서 사용한 방법과 유사한 방식으로 정의 하지만, QWidget 과 Ui::CalculatorForm 을 동시에 상속한다는 점에서 다릅니다.

class CalculatorForm : public QWidget, private Ui::CalculatorForm
{
    Q_OBJECT

public:
    CalculatorForm(QWidget *parent = 0);

private slots:
    void on_inputSpinBox1_valueChanged(int value);
    void on_inputSpinBox2_valueChanged(int value);
};

We inherit Ui::CalculatorForm privately to ensure that the user interface objects are private in our subclass. We can also inherit it with the public or protected keywords in the same way that we could have made ui public or protected in the previous case.

우리는 Ui::CalculatorForm 을 프라이빗 형태로 상속하여, 사용자 인터페이스 객체들이 우리 클래스에서 프라이빗 형태로 존재함을 보장 합니다. 우리는 ui 를 public 또는 protected 키워드를 사용해 퍼브릿 또는 프로텍티드 형태로 상속 할 수도 있습니다. (가능성만 두고 있으며 실제로는 잘 사용하지 않음)

The constructor for the subclass performs many of the same tasks as the constructor used in the single inheritance example:

서브클래스를 위한 생성자는 단일 상속 예제에서 사용되는 다수의 작업들과 동일하게 동작합니다.

CalculatorForm::CalculatorForm(QWidget *parent)
    : QWidget(parent)
{
    setupUi(this);
}

In this case, the widgets used in the user interface can be accessed in the same say as a widget created in code by hand. We no longer require the ui prefix to access them.

이 경우, 사용자 인터페이스에서 사용되는 위젯들은 직접 작성된 위젯에서와 같은 방식으로 접근이 가능합니다. 우리는 더 이상 이들을 접근하는데, ui 접두어를 필요로 하지 않습니다.

Reacting to Language Changes

언어 변화에 대응하기

Qt notifies applications if the user interface language changes by sending an event of the type QEvent::LanguageChange. To call the member function retranslateUi() of the user interface object, we reimplement QWidget::changeEvent() in the form class, as follows:

Qt 는 사용자 인터페이스 언어 변경 여부가 있다면, QEvent::LanguageChagne 라는 이벤트를 전달 하는 방식으로 응용프로그램들에게 알려줍니다. 사용자 인터페이스 객체의 retranlateUi() 를 호출하기 위해서는, 폼 클래스의 QWidget::changeEvent() 를 다음과 같이 재구현해야 합니다.

void CalculatorForm::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
   }
}

Run Time Form Processing

실행-중(런타임) 폼 처리

Alternatively, forms can be processed at run time, producing dynamically- generated user interfaces. This can be done using the QtUiTools module that provides the QUiLoader class to handle forms created with Qt Designer.

다른 방법으로, 폼(정보) 들은 실행 중에 처리가 될 수 있기에, 동적으로 사용자 인터페이스를 생성할 수 있습니다. 이는 Qt 디자이너로 만들어진 폼들을 처리하는 클래스인 QUiLoader 가 제공하는 QtUiTools 모듈을 사용해서 가능해집니다.

The UiTools Approach

UiTools 접근

A resource file containing a UI file is required to process forms at run time. Also, the application needs to be configured to use the QtUiTools module. This is done by including the following declaration in a qmake project file, ensuring that the application is compiled and linked appropriately.

실행 중에 폼(정보) 를 처리를 위해 UI 파일을 포함하는 리소스(자원) 파일이 요구됩니다. 또한 응용 프로그램은 QtUiTools 모듈을 사용하기 위해 설정이 되어 있어야 합니다. 이는 qmake 프로젝트 파일을 다음과 같이 선언되어 응용 프로그램이 적절히 컴파일되고 링크 작업을 보장 받을 수 있어야 합니다.

QT += uitools

The QUiLoader class provides a form loader object to construct the user interface. This user interface can be retrieved from any QIODevice, e.g., a QFile object, to obtain a form stored in a project's resource file. The QUiLoader::load() function constructs the form widget using the user interface description contained in the file.

QUiLoader 클래스는 사용자 인터페이스를 생성하는 폼 로더(불러오기) 오브젝트를 제공합니다. 이 사용자 인터페이스는 프로젝트의 리소스 파일에 저장된 폼을 가져오기 위해 어떠한 QIODevice 객체를 사용하여 (예. QFile 객체) 가져 졸 수 있습니다. QUiLoader::load() 함수는 파일에 포함된 사용자 인터페이스를 사용하여 폼 위젯을 생성합니다.

The QtUiTools module classes can be included using the following directive:

QtTools 모듈 클래스들은 다음과 같은 선언문을 통해서 포함될 수 있습니다.

#include <QtUiTools>

The QUiLoader::load() function is invoked as shown in this code from the Text Finder example:

QUiLoader::load() 함수는 Text Finder 예제를 통해서 아래 코드 처럼 호출 됩니다.

QWidget* TextFinder::loadUiFile()
{
    QUiLoader loader;

    QFile file(":/forms/textfinder.ui");
    file.open(QFile::ReadOnly);

    QWidget *formWidget = loader.load(&file, this);
    file.close();

    return formWidget;
}

In a class that uses QtUiTools to build its user interface at run time, we can locate objects in the form using qFindChild(). For example, in the following code, we locate some components based on their object names and widget types:

실행-중 (런타임) 사용자 인터페이스를 만들기 위해, QtUiTools 를 사용하는 클래스는 qFindChild() 함수를 사용하여 객체들을 찾습니다. 예를 들어 다음 코드에서 객체의 이름과 위젯 형태를 기반으로 몇몇 컴포넌트들을 찾습니다.

    ui_findButton = findChild<QPushButton*>("findButton");
    ui_textEdit = findChild<QTextEdit*>("textEdit");
    ui_lineEdit = findChild<QLineEdit*>("lineEdit");

Processing forms at run-time gives the developer the freedom to change a program's user interface, just by changing the UI file. This is useful when customizing programs to suit various user needs, such as extra large icons or a different colour scheme for accessibility support.

폼들을 실행중으로 처리하는 것은, 개발자에게 프로그램의 사용자 인터페이스를 변경하는 자유를 제공해줍니다. 이는 추가적으로 더 큰 아이콘이나 접근성 제공을 위한 다른 색 목록을 제공하는 다양한 사용자 요구를 부합하기 위한 프로그램을 커스터마이징(변경) 할 때 유용합니다.

Automatic Connections

자동 연결

The signals and slots connections defined for compile time or run time forms can either be set up manually or automatically, using QMetaObject's ability to make connections between signals and suitably-named slots.

시그널과 슬롯 연결은 시그널과 적절히-명명된 슬롯간의 연결을 만들기 위해 QMetaObject의 기능을 사용하여 컴파일 시점 또는 실행-중(런타임) 에 수동 또는 자동으로 정의 됩니다.

Generally, in a QDialog, if we want to process the information entered by the user before accepting it, we need to connect the clicked() signal from the OK button to a custom slot in our dialog. We will first show an example of the dialog in which the slot is connected by hand then compare it with a dialog that uses automatic connection.

일반적으로 QDialog 에서, 만약 우리가 사용자가 받아들이기 전에 사용자가 입력한 정보를 처리하고 싶다면 우리는 clicked() 시그널과 우리 대화창에 있는 OK 버튼과 연결된 커스텀 슬롯간 연결을 해야합니다. 우리는 대화창에 있는 어떤 슬롯과 연결되는지 예를 보여주고, 그리고 나서 자동 연결을 사용한 대화창과 비교 해야할 것입니다.

A Dialog Without Auto-Connect

자동-연결을 사용하지 않는 대화창

We define the dialog in the same way as before, but now include a slot in addition to the constructor:

우리는 이전과 동일한 방식으로 대화창을 정의하지만, 지금은 생성자에서 추가로 슬롯 하나를 포함합니다.

class ImageDialog : public QDialog, private Ui::ImageDialog
{
    Q_OBJECT

public:
    ImageDialog(QWidget *parent = 0);

private slots:
    void checkValues();
};

The checkValues() slot will be used to validate the values provided by the user.

사용자가 제공하는 다양한 값들을 검증하는데 checkValues() 슬롯이 사용될 것입니다.

In the dialog's constructor we set up the widgets as before, and connect the Cancel button's clicked() signal to the dialog's reject() slot. We also disable the autoDefault property in both buttons to ensure that the dialog does not interfere with the way that the line edit handles return key events:

대화창의 생성자는 이전과 같이 설정하고, 그리고 Cancel 버튼의 clicked() 시그널을 대화창의 reject() 슬롯과 연결합니다. 그리고 autoDefault 프로퍼티 (속성값) 을 모두 지정하여, 대화창이 줄-편집 중에 처리되는 리턴 키에 방해 받지 말아 달라고 선언합니다.

ImageDialog::ImageDialog(QWidget *parent)
    : QDialog(parent)
{
    setupUi(this);
    okButton->setAutoDefault(false);
    cancelButton->setAutoDefault(false);
    ...
    connect(okButton, SIGNAL(clicked()), this, SLOT(checkValues()));
}

We connect the OK button's clicked() signal to the dialog's checkValues() slot which we implement as follows:

우리는 OK 버튼의 clicked() 시그널과 대화창의 checkValues() 슬롯을 연결하여 다음과 같이 구현 합니다.

void ImageDialog::checkValues()
{
    if (nameLineEdit->text().isEmpty())
        (void) QMessageBox::information(this, tr("No Image Name"),
            tr("Please supply a name for the image."), QMessageBox::Cancel);
    else
        accept();
}

This custom slot does the minimum necessary to ensure that the data entered by the user is valid - it only accepts the input if a name was given for the image.

이 커스텀 슬롯은 사용자가 입력한 정보가 유효한지 최소한의 필요 조건을 확인 합니다 - 주어진 그램에 맞는 이름이 맞는지만 확인해서 받아 줍니다.

Widgets and Dialogs with Auto-Connect

자동-연결 을 사용한 위젯과 대화창들

Although it is easy to implement a custom slot in the dialog and connect it in the constructor, we could instead use QMetaObject's auto-connection facilities to connect the OK button's clicked() signal to a slot in our subclass. uic automatically generates code in the dialog's setupUi() function to do this, so we only need to declare and implement a slot with a name that follows a standard convention:

대화창에 쓸 커스텀 슬롯을 구현하여 생성자에서 연결하는 작업은 쉽긴하지만, 이를 대신하여 우리의 서브클래스에 있는 슬롯이 OK 버튼의 clicked() 시그널과 연결하기 위해 QMetaObject 의 자동-연결 기능을 사용할 수 있습니다.

void on_<object name>_<signal name>(<signal parameters>);

Using this convention, we can define and implement a slot that responds to mouse clicks on the OK button:

이러한 이름 명명법(사용법) 을 통해 우리는 마우스로 OK 버튼을 눌렀을 때  반응하는 슬롯을 구현하고 정의할 수 있습니다.

class ImageDialog : public QDialog, private Ui::ImageDialog
{
    Q_OBJECT

public:
    ImageDialog(QWidget *parent = 0);

private slots:
    void on_okButton_clicked();
};

Another example of automatic signal and slot connection would be the Text Finder with its on_findButton_clicked() slot.

또 다른 시그널과 슬롯 자동 연결 예로, on_findButton_clicked() 슬롯을 들 수 있습니다.

We use QMetaObject's system to enable signal and slot connections:

우리는 QMetaObject 의 시스템을 사용해 시그널과 슬롯 연결을 활성화 시킵니다.

    QMetaObject::connectSlotsByName(this);

This enables us to implement the slot, as shown below:

이는 슬롯을 아래와 같이 구현하는 것을 허용해줍니다.

void TextFinder::on_findButton_clicked()
{
    QString searchString = ui_lineEdit->text();
    QTextDocument *document = ui_textEdit->document();

    bool found = false;

    if (isFirstTime == false)
        document->undo();

    if (searchString.isEmpty()) {
        QMessageBox::information(this, tr("Empty Search Field"),
                "The search field is empty. Please enter a word and click Find.");
    } else {

        QTextCursor highlightCursor(document);
        QTextCursor cursor(document);

        cursor.beginEditBlock();
    ...
        cursor.endEditBlock();
        isFirstTime = false;

        if (found == false) {
            QMessageBox::information(this, tr("Word Not Found"),
                "Sorry, the word cannot be found.");
        }
    }
}

Automatic connection of signals and slots provides both a standard naming convention and an explicit interface for widget designers to work to. By providing source code that implements a given interface, user interface designers can check that their designs actually work without having to write code themselves.

시그널과 슬롯의 자동 연결은 위젯 디자이너가 작업하기 위한 표준 이름 명명법과 명시적인 인터페이스를 동시에 제공해줍니다. 주어진 인터페이스를 구현하는 소스 코드를 제공함으로, 사용자 인터페이스 디자이너들은 코드를 작성하지 않고도, (예상하여) 디자인한 방식대로 실제 동작되는지를 확인할 수 있습니다.

© 2015 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.