콤보박스는 드롭 다운 메뉴입니다. ComboBox와 ComboBoxText의 차이점이라면 ComboBoxText는 텍스트만 있는 위젯이고, 완전한 ComboBox는 분기 옵션이나, 각 선택 항목의 그림을 보여주는 ListStore나 TreeStore(기본적으로 스프레드 시트 같음)를 사용하는 위젯입니다.
완전한 기능을 갖춘 ComboBox가 필요하거나, ListStore와 TreeStore를 사용하지 않은 이상 가능하다면 ComboBoxText를 사용하는게 훨씬 간단합니다.
#!/usr/bin/gjs
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
이 프로그램을 실행할 때 가져올 라이브러리입니다. 시작 부분에 항상 gjs가 필요함을 알리는 줄을 작성해야 함을 기억하십시오.
const ComboBoxTextExample = new Lang.Class ({
Name: 'ComboBoxText Example',
// Create the application itself
_init: function () {
this.application = new Gtk.Application ({
application_id: 'org.example.jscomboboxtext'});
// Connect 'activate' and 'startup' signals to the callback functions
this.application.connect('activate', Lang.bind(this, this._onActivate));
this.application.connect('startup', Lang.bind(this, this._onStartup));
},
// Callback function for 'activate' signal presents windows when active
_onActivate: function () {
this._window.present ();
},
// Callback function for 'startup' signal builds the UI
_onStartup: function () {
this._buildUI ();
},
이 예제의 모든 코드는 MessageDialogExample 클래스에 넣었습니다. 위 코드에서는 위젯과 창을 담아둘 Gtk.Application을 만들었습니다.
// Build the application's UI
_buildUI: function () {
// Create the application window
this._window = new Gtk.ApplicationWindow ({
application: this.application,
window_position: Gtk.WindowPosition.CENTER,
title: "Welcome to GNOME",
default_width: 200,
border_width: 10 });
_buildUI 함수는 프로그램 사용자 인터페이스를 만드는 모든 코드를 넣는 곳입니다. 첫 단계에서는 모든 위젯을 우겨넣을 새 Gtk.ApplicationWindow를 만듭니다.
// Create the combobox
this._comboBoxText = new Gtk.ComboBoxText();
// Populate the combobox
let distros = ["Select distribution", "Fedora", "Mint", "Suse"];
for (let i = 0; i < distros.length; i++)
this._comboBoxText.append_text (distros[i]);
this._comboBoxText.set_active (0);
// Connect the combobox's 'changed' signal to our callback function
this._comboBoxText.connect ('changed', Lang.bind (this, this._onComboChanged));
ComboBoxText를 만들고 나서
ComboBoxText를 갖추고 나서 첫번째 항목을 표시하여 ComboBoxText를 누르기 전에 "Select distribution" 줄이 나타나게 하겠습니다. 그 다음
ComboBoxText에 항목을 추가하려면
// Add the combobox to the window
this._window.add (this._comboBoxText);
// Show the window and all child widgets
this._window.show_all();
},
마지막으로 ComboBoxText를 창에 추가하고, 창 자신과 위젯을 나타내게 하겠습니다.
_onComboChanged: function () {
// The responses we'll use for our messagedialog
let responses = ["",
"Fedora is a community distro sponsored by Red Hat.",
"Mint is a popular distro based on Ubuntu.",
"SUSE is a name shared by two separate distros."];
배포판 선택 기반으로 메시지를 보여주는 MessageDialog 팝업을 만들려고 합니다. 우선, 사용할 응답 배열을 만들겠습니다. ComboBoxText의 첫 문자열은 그냥 "Select distribution" 메시지니까, 배열의 첫번째 문자열은 비워두겠습니다.
// Which combobox item is active?
let activeItem = this._comboBoxText.get_active();
// No messagedialog if you chose "Select distribution"
if (activeItem != 0) {
this._popUp = new Gtk.MessageDialog ({
transient_for: this._window,
modal: true,
buttons: Gtk.ButtonsType.OK,
message_type: Gtk.MessageType.INFO,
text: responses[activeItem]});
// Connect the OK button to a handler function
this._popUp.connect ('response', Lang.bind (this, this._onDialogResponse));
// Show the messagedialog
this._popUp.show();
}
},
MessageDialog를 나타내기 전, "Select distribution" 메시지를 선택하지 않았는지 우선 확인해야 합니다. 확인하고 나면 ComboBoxText의 선택 항목과 관련하여 배열의 항목 텍스트를 설정합니다. 선택 항목의 숫자 ID를 반환하는
MessageDialog를 만들고 나면, _onDialogResponse 함수에 반응 시그널을 연결하고 MessageDialog를 나타내게 하겠습니다.
_onDialogResponse: function () {
this._popUp.destroy ();
}
});
MessageDialog에는 확인 단추만 있기 때문에 response_id에서 어떤 단추를 눌렀는지 굳이 확인할 필요가 없습니다. 그냥 띄운 창을 닫기만 하면 됩니다.
// Run the application
let app = new ComboBoxTextExample ();
app.application.run (ARGV);
마지막으로, 코드 작성을 마무리한 ComboBoxTextExample 클래스의 새 인스턴스를 만들고, 프로그램 실행을 구성하겠습니다.
#!/usr/bin/gjs
imports.gi.versions.Gtk = '3.0';
const Gtk = imports.gi.Gtk;
class ComboBoxTextExample {
// Create the application itself
constructor() {
this.application = new Gtk.Application ({
application_id: 'org.example.jscomboboxtext'});
// Connect 'activate' and 'startup' signals to the callback functions
this.application.connect('activate', this._onActivate.bind(this));
this.application.connect('startup', this._onStartup.bind(this));
}
// Callback function for 'activate' signal presents windows when active
_onActivate() {
this._window.present ();
}
// Callback function for 'startup' signal builds the UI
_onStartup() {
this._buildUI();
}
// Build the application's UI
_buildUI() {
// Create the application window
this._window = new Gtk.ApplicationWindow ({
application: this.application,
window_position: Gtk.WindowPosition.CENTER,
title: "Welcome to GNOME",
default_width: 200,
border_width: 10 });
// Create the combobox
this._comboBoxText = new Gtk.ComboBoxText();
// Populate the combobox
let distros = ["Select distribution", "Fedora", "Mint", "Suse"];
for (let i = 0; i < distros.length; i++)
this._comboBoxText.append_text (distros[i]);
this._comboBoxText.set_active (0);
// Connect the combobox's 'changed' signal to our callback function
this._comboBoxText.connect ('changed', this._onComboChanged.bind(this));
// Add the combobox to the window
this._window.add (this._comboBoxText);
// Show the window and all child widgets
this._window.show_all();
}
_onComboChanged() {
// The responses we'll use for our messagedialog
let responses = ["",
"Fedora is a community distro sponsored by Red Hat.",
"Mint is a popular distro based on Ubuntu.",
"SUSE is a name shared by two separate distros."];
// Which combobox item is active?
let activeItem = this._comboBoxText.get_active();
// No messagedialog if you chose "Select distribution"
if (activeItem != 0) {
this._popUp = new Gtk.MessageDialog ({
transient_for: this._window,
modal: true,
buttons: Gtk.ButtonsType.OK,
message_type: Gtk.MessageType.INFO,
text: responses[activeItem]});
// Connect the OK button to a handler function
this._popUp.connect ('response', this._onDialogResponse.bind(this));
// Show the messagedialog
this._popUp.show();
}
}
_onDialogResponse() {
this._popUp.destroy ();
}
};
// Run the application
let app = new ComboBoxTextExample ();
app.application.run (ARGV);
이 예제는 다음 참고자료가 필요합니다:
Gtk.Application
Gtk.ApplicationWindow
Gtk.ComboBoxText
Gtk.MessageDialog