【QT】ComboBox


【目的】

  1. 主要是了解 combox 的用法。

【程式】

  • 建立一個物件繼承QWidget(order.h)
    #ifndef ORDER_H
    #define ORDER_H
    #include <QWidget>
    class  OrderMenu: public QWidget {
            Q_OBJECT
    
    private slots:
            void PrintOrder(const QString &str);
    };
    #endif
  • 示範如何知道從combobox傳過來的字串(main.cpp)
    #include <QApplication>
    #include <QWidget>
    #include <QLabel>
    #include <QComboBox>
    #include <QVBoxLayout>
    #include <QtDebug>
    #include <QObject>
    #include "order.h"
    
    void OrderMenu::PrintOrder(const QString &str)
    {
      QString prefix = tr("Your favorite food is");
    
      if (str == QObject::tr("Donut"))
        qDebug() << prefix << str;
      else if (str == QObject::tr("Pizza"))
        qDebug() << prefix << str;
      else
        qDebug() << prefix << str;
    }
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
        QWidget *order = new OrderMenu;
        order->setWindowTitle("Favorite food");
        order->resize(250, 100);
    
        QLabel *label = new QLabel(QObject::tr("Choose your favorite food"));
        QComboBox *combo = new QComboBox;
        combo->insertItem(0, "Donut");
        combo->insertItem(1, "Pizza");
    
        QVBoxLayout *layout = new QVBoxLayout;
        layout->addWidget(label);
        layout->addWidget(combo);    
        QObject::connect(combo, SIGNAL(activated(const QString &)),
         order, SLOT(PrintOrder(const QString &)));    
        order->setLayout(layout);
        order->show();
        return app.exec();
    }

【結果】

  1. 顯示視窗
    image
  2. 結果是用 qDebug 列印,這邊不特別抓圖了。
 

Ed32. Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com