如何更改QComboBox项目的高度大小?

How to change QComboBox items height size?

本文关键字:高度 何更改 QComboBox 项目      更新时间:2023-10-16

如何更改QComboBox项目的高度大小?

我只想改变高度 - 我需要它更大。

奇怪的是,没有任何用于此目的的功能。

第一个选项是设置一个新的弹出窗口,例如QListView并使用Qt样式表更改大小:

#include <QApplication>
#include <QComboBox>
#include <QListView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox combo;
QListView *view = new QListView(&combo);
view->setStyleSheet("QListView::item{height: 100px}");
combo.setView(view);
combo.addItems({"A", "B", "C", "D", "E", "F"});
combo.show();
return a.exec();
}

另一种选择是将委托设置为调整大小的弹出窗口:

#include <QApplication>
#include <QComboBox>
#include <QStyledItemDelegate>
#include <QAbstractItemView>
class PopupItemDelegate: public QStyledItemDelegate
{
public:
using QStyledItemDelegate::QStyledItemDelegate;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
QSize s = QStyledItemDelegate::sizeHint(option, index);
s.setHeight(60);
return s;
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox combo;
combo.view()->setItemDelegate(new PopupItemDelegate(&combo));
combo.addItems({"A", "B", "C", "D", "E", "F"});
combo.show();
return a.exec();
}

您可以通过setView方法控制高度并QSS

self.comboBox.setView(QtWidgets.QListView())

QSS

QListView::item {
height: 30px;
}

示例代码:

import sys
from PyQt5 import QtWidgets, QtCore, QtGui

class MainWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.__ui__()
self.__style__()
def __ui__(self):
self.layout = QtWidgets.QVBoxLayout()
self.comboBox = QtWidgets.QComboBox()
self.comboBox.setView(QtWidgets.QListView())
self.comboBox.addItems(["one", "too", "three", "four", "five", "six"])
self.layout.addWidget(self.comboBox)
self.setLayout(self.layout)
def __style__(self):
self.comboBox.setStyleSheet("QListView::item {height:30px;}")
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MainWidget()
widget.show()
sys.exit(app.exec_())