定制QT有标题的扁平化下拉框控件-QComboBox+QLineEdit+QListView

时间:2015-07-22 22:20:35   收藏:0   阅读:5972

关键字:QT,QComboBox,QLineEdit,QListView

OS:Windows 7

 

问题链接:QComboBox: Can we make the entire combobox clickable, not just the dropdown button (arrow) itself?

 

为了使整个combobox都是可点击的,所以加个QTComboBoxButton类继承QLineEdit,在mousePressEvent里面showPopup。

class QTComboBoxButton : public QLineEdit
{
    Q_OBJECT
public:
    QTComboBoxButton(QWidget *parent = 0);
    ~QTComboBoxButton();

protected:
    void mousePressEvent(QMouseEvent *);
};

QTComboBoxButton::QTComboBoxButton(QWidget *parent /* = 0 */) :
    QLineEdit(parent)
{
}

QTComboBoxButton::~QTComboBoxButton()
{
}

void QTComboBoxButton::mousePressEvent(QMouseEvent * e)
{
    QComboBox* combo = dynamic_cast<QComboBox*>(parent());
    if(combo)
        combo->showPopup();
}

QComboBox+QLineEdit+QListView的使用如下:

QComboBox* myCombo = new QComboBox;
    myCombo->setView(new QListView());
    myCombo->setEditable(true);
    myCombo->setLineEdit(new QTComboBoxButton(m_pAnswer));
    myCombo->lineEdit()->setReadOnly(true);
    myCombo->addItem("Option1");
    myCombo->addItem("Option2");
    myCombo->addItem("Option3");
    myCombo->setMaxVisibleItems(myCombo->count());
    myCombo->lineEdit()->setText("Please select");
    QString arrowImagePath = "c:\arrow.png";
    myCombo->setStyleSheet("QComboBox {font-family: \"Arial\"; font-size: 13px; padding: 3px 0x 3px 5px;}"
        "QComboBox::drop-down {subcontrol-origin: padding; subcontrol-position: top right; width: 30 px; border: 0px;}"
        "QComboBox::down-arrow {image: url("+ arrowImagePath +");}");
    myCombo->view()->setStyleSheet("QListView {font-family: \"Arial\"; font-size: 13px; outline: 0px;}"
        "QListView::item {padding: 3px 0x 3px 5px; border-width: 0px;}"
        "QListView::item:selected {background-color: rgb(74, 144, 226);}");

UI效果如下图:

技术分享

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!