【问题标题】:How to change QComboBox items height size?如何更改 QComboBox 项目的高度大小?
【发布时间】:2018-10-12 11:45:22
【问题描述】:

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

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

奇怪的是没有任何用于此目的的函数。

【问题讨论】:

    标签: c++ qt qt5 qcombobox


    【解决方案1】:

    第一个选项是设置一个新的弹出窗口,例如 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();
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 2012-09-24
        • 2014-01-06
        • 1970-01-01
        相关资源
        最近更新 更多