[QT] How to adjust the spacing or height of the comboBox drop-down list and center the font of the drop-down list

The default QComboBox drop-down list looks very crowded and not beautiful.

So how to adjust the spacing or height of the comboBox drop-down list? Please see the method below:

1. Use style sheets, very simple

The easiest way, two lines of code can be solved:

ui->comboBox->setView(new QListView());  //必须设置
setStyleSheet("QComboBox QAbstractItemView::item{height:28px;}");

2. Use QListWidget to achieve

This method can also realize the display position of the current item or drop-down list item in its comboBox (left, right, center)

QStringList list;
list << tr("项目1") << tr("项目2") << tr("项目3");
QListWidget* listWidget = new QListWidget(this);
for (int i = 0; i < list.count(); ++i) {
    
    
	QListWidgetItem* item = new QListWidgetItem(list.at(i));
	item->setTextAlignment(Qt::AlignCenter);  //下拉列表项显示在中间
	// item->setTextAlignment(Qt::AlignLeft);  //下拉列表项显示在左边
	// item->setTextAlignment(Qt::AlignRight);  //下拉列表项显示在右边
	listWidget->addItem(item);
}

ui->comboBox->setModel(listWidget->model());
ui->comboBox->setView(listWidget);

QLineEdit* lineEdit = new QLineEdit();
lineEdit->setReadOnly(true);
lineEdit->setAlignment(Qt::AlignCenter);  //当前项显示在中间
// lineEdit->setAlignment(Qt::AlignLeft);  //当前项显示在左边
// lineEdit->setAlignment(Qt::AlignRight);  //当前项显示在右边
ui->comboBox->setLineEdit(lineEdit);
}

Guess you like

Origin blog.csdn.net/WL0616/article/details/130231314