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

How to change QComboBox items height size?

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

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

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

可以通过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_())

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

#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();
}