QListBox與QComboBox在視窗中是相當常見的兩個元件,在這邊先簡單的介紹這兩個元件的基本配置與外觀。
請編輯main.cpp:
#include <qapplication.h> #include <qvbox.h> #include <qhbox.h> #include <qlabel.h> #include <qcombobox.h> #include <qlistbox.h> #include <qpixmap.h>
int main(int argc, char **argv) { QApplication app(argc, argv); QVBox *vbox = new QVBox(); QHBox *hbox = new QHBox(vbox); QLabel *label;
hbox = new QHBox(vbox); label = new QLabel("ListBox: ", hbox); hbox->setSpacing(10); QListBox *listbox = new QListBox(hbox); listbox->insertItem("listbox item with text"); listbox->insertItem(QPixmap("icon.xpm"), "listbox item with icon"); listbox->insertItem(QPixmap("dog.xpm"), "listbox item with large icon");
hbox = new QHBox(vbox); hbox->setSpacing(10); label = new QLabel("&ComboBox: ", hbox); QComboBox *comboBox = new QComboBox(FALSE, hbox); comboBox->insertItem("combox item with text"); comboBox->insertItem(QPixmap("fileopen.xpm"), "combox item with icon"); label->setBuddy(comboBox);
app.setMainWidget(vbox); vbox->show();
return app.exec(); }
這個程式使用了QVBox與QHBox來作版面配置,QVBox被設定為主Widget,而兩個QHBox配置在QVBox中。
這幾行配置QListBox,主要在於insertItem的使用,我們可以在當中插入文字或圖片,圖片檔案的讀取我們使用QPixmap來讀取點陣圖:
QListBox *listbox = new QListBox(hbox);
listbox->insertItem("listbox item with text");
listbox->insertItem(QPixmap("icon.xpm"), "listbox item with icon");
配置QComboBox與當中的項目,其中FALSE表示設定項目為不可編輯:
QComboBox *comboBox = new QComboBox(FALSE, hbox);
comboBox->insertItem("combox item with text");
comboBox->insertItem(QPixmap("fileopen.xpm"), "combox item with icon");
設定快捷鍵(accelerator key),這是QLabel所獨有的方法,我們使用&來指定快捷鍵為C,所以當我們按下Alt+C時會跳至指定的QComboBox:
label = new QLabel("&ComboBox: ", hbox);
......
label->setBuddy(comboBox);
程式中的*.xpm是我們所使用的圖檔,這個程式的執行外觀如下圖所示:

|
|