Qt ComboBox 下拉框设置多列
通过设置listview实现。
class MultiColumnComboBoxItemDelegate;
class MultiColumnComboBoxListView;
class MultiColumnComboBox : public QComboBox
{
Q_OBJECT
public:
explicit MultiColumnComboBox(QWidget *parent = nullptr);
~MultiColumnComboBox();
protected:
void showPopup() override;;
private:
MultiColumnComboBoxItemDelegate *m_Delegate = nullptr;
MultiColumnComboBoxListView *m_ListView = nullptr;
};
class MultiColumnComboBoxListView: public QListView
{
Q_OBJECT
public:
explicit MultiColumnComboBoxListView(QWidget *parent = nullptr);
~MultiColumnComboBoxListView();
};
class MultiColumnComboBoxItemDelegate: public QStyledItemDelegate
{
Q_OBJECT
public:
MultiColumnComboBoxItemDelegate(QObject* parent = nullptr);
~MultiColumnComboBoxItemDelegate();
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
private:
int m_width;
friend class MultiColumnComboBox;
};
MultiColumnComboBox::MultiColumnComboBox(QWidget *parent)
: QComboBox(parent)
, m_Delegate(new MultiColumnComboBoxItemDelegate(this))
, m_ListView(new MultiColumnComboBoxListView(this))
{
setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow);
setView(m_ListView);
setItemDelegate(m_Delegate);
setMaxVisibleItems(6);
setFocusPolicy(Qt::ClickFocus);
}
MultiColumnComboBox::~MultiColumnComboBox()
{
if(nullptr != m_Delegate)
{
delete m_Delegate;
m_Delegate = nullptr;
}
if(nullptr != m_ListView)
{
delete m_ListView;
m_ListView = nullptr;
}
}
void MultiColumnComboBox::showPopup()
{
int rowHeight = view()->sizeHintForRow(0);
int rowNum = model()->rowCount();
int showRows = 0;
for(int curRow = 0; curRow<rowNum; curRow++)
{
if(!m_ListView->isRowHidden(curRow))
{
showRows++;
}
}
int maxrow = showRows;
if(maxrow > maxVisibleItems())
{
int curCloumn = ceil(double(maxrow) / double(maxVisibleItems()));
m_Delegate->m_width = this->width();
view()->setMinimumWidth(curCloumn * this->width() + 5);
maxrow = ceil(double(maxrow) / double(curCloumn));
if(maxrow < maxVisibleItems())
{
setMaxVisibleItems(maxrow);
}
}
else
{
m_Delegate->m_width = this->width();
view()->setMinimumWidth(this->width() + 5);
}
QComboBox::showPopup();
view()->setMinimumHeight(rowHeight * maxrow + 5);
}
MultiColumnComboBoxListView::MultiColumnComboBoxListView(QWidget *parent)
:QListView(parent)
{
setSpacing(0);
setResizeMode(QListView::Adjust);
setFlow(QListView::TopToBottom);
setWrapping(true);
}
MultiColumnComboBoxListView::~MultiColumnComboBoxListView()
{
}
MultiColumnComboBoxItemDelegate::MultiColumnComboBoxItemDelegate(QObject *parent)
:QStyledItemDelegate(parent)
{
}
MultiColumnComboBoxItemDelegate::~MultiColumnComboBoxItemDelegate()
{
}
QSize MultiColumnComboBoxItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
auto originalSize = QStyledItemDelegate::sizeHint(option, index);
originalSize.setWidth(m_width);
return originalSize;
}