1. 程式人生 > >QComboBox下拉列表樣式美化定義

QComboBox下拉列表樣式美化定義

Qt Assistant中官方提供的指令碼定義樣例如下:
QComboBox {
    border: 1px solid gray;
    border-radius: 3px;
    padding: 1px 18px 1px 3px;
    min-width: 6em;
}

QComboBox:editable {
    background: white;
}

QComboBox:!editable, QComboBox::drop-down:editable {
     background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                 stop: 0 #E1E1E1, stop: 0.4 #DDDDDD,
                                 stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3);
}

/* QComboBox gets the "on" state when the popup is open */
QComboBox:!editable:on, QComboBox::drop-down:editable:on {
    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                stop: 0 #D3D3D3, stop: 0.4 #D8D8D8,
                                stop: 0.5 #DDDDDD, stop: 1.0 #E1E1E1);
}

QComboBox:on { /* shift the text when the popup opens */
    padding-top: 3px;
    padding-left: 4px;
}

QComboBox::drop-down {
    subcontrol-origin: padding;
    subcontrol-position: top right;
    width: 15px;

    border-left-width: 1px;
    border-left-color: darkgray;
    border-left-style: solid; /* just a single line */
    border-top-right-radius: 3px; /* same radius as the QComboBox */
    border-bottom-right-radius: 3px;
}

QComboBox::down-arrow {
    image: url(/usr/share/icons/crystalsvg/16x16/actions/1downarrow.png);
}

QComboBox::down-arrow:on { /* shift the arrow when popup is open */
    top: 1px;
    left: 1px;
}
遺憾的是沒有上面的指令碼中沒有提供QComboBox下拉列表的樣式定義。 QComboBox下拉列表不支援直接定義樣式,需要在原始碼中使用到樣式委託物件QStyledItemDelegate
	//用於下拉框item的樣式美化
	QStyledItemDelegate* itemDelegate = new QStyledItemDelegate();
	ui.comboBox1->setItemDelegate(itemDelegate);
然後再在qss指令碼中定義QAbstractItemView相關樣式,以下是簡易示例:
QComboBox QAbstractItemView
{
     border: 1px solid rgb(161,161,161);
}

QComboBox QAbstractItemView::item
{
    height: 24px;
}

QComboBox QAbstractItemView::item:selected
{	
    background-color: rgba(54, 98, 180);
}