下拉选项单--QComboBox和ComboBox

下拉菜单可通过两种方式来实现

1、通过QComboBox调用addItem实现添加下拉选项

#include 
#include 
#include 
#include 

int main(int argc, char *argv[])
{

    QApplication app(argc, argv);
    QWidget * window = new QWidget;
    window->setWindowTitle("Hybird");
    window->resize(240,320);

    QComboBox * combox = new QComboBox;
    combox->addItem("Apple");
    combox->addItem("Banana");
    combox->addItem("Pear");

    QComboBox *comboxIcon = new QComboBox;
    comboxIcon->addItem(QIcon(":/images/Apple.jpg"),"Apple");
    comboxIcon->addItem(QIcon(":/images/Banana.jpg"),"Banana");
    QVBoxLayout * layout = new QVBoxLayout;
    layout->addWidget(combox);
    layout->addWidget(comboxIcon);
    window->setLayout(layout);
    window->show();
    return app.exec();
}

需要注意的是:添加图片时,要手动将图片添加到.qrc文件中。

2、在QML的ComboBox空间实现下拉控件的实现

     简单实现下拉菜单其中下拉选项包含Banana、Apple、Pear选项

··

    ComboBox{

        currentIndex: 1
        width: 100
        height: 30
        model: ["Banana","Apple","pear"]
    }

··

下面的这个例子,可以实现基本的下拉选项,而且我们可以改变下拉框的颜色以及外边框的颜色,相关代码示例如下:

··

    ComboBox{

        currentIndex:  1
        width: 100
        height: 30
        style:ComboBoxStyle{
            background: Item {
                id: combobak
                Rectangle{
                    anchors.fill: parent
                    color: "Gray"
                    border.width: 2
                    border.color: "Green"
                }
                Image {
                    id: comboimage
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.right: parent.right
                    anchors.rightMargin: dropDownButtonWidth / 2
                    source: "/images/arrow-down.png"
                }
 
  
            }
        }
        model: ListModel{
            ListElement{name:"Banana"}
            ListElement{name:"Apple"}
        }
    }

··

 

你可能感兴趣的:(Qt编程)