1. 使用示例
例如让下拉列表右边和Combobox对齐:
(参数 originalRect 的位置是默认位置,也就是左对齐)
CustomCombobox* cb = new CustomCombobox(this);
cb->setDownListPosSource([&](QRect originalRect) -> QRect {
QAbstractItemView *view = cb->view();
originalRect.setX(originalRect.x() - view->width() + cb->width());
return originalRect;
});
2. CustomCombobox.h
#pragma once
#include <QComboBox>
class CustomCombobox : public QComboBox {
Q_OBJECT
public:
using super = QComboBox;
void setDownListPosSource(std::function<QRect(QRect originalRect)> positionSource);
CustomCombobox(QWidget *parent = nullptr);
private:
class Impl;
std::shared_ptr<Impl> m_impl = nullptr;
};
3. CustomCombobox.cpp
#include "CustomCombobox.h"
#include <QProxyStyle>
class PositionStyle : public QProxyStyle {
public:
using super = QProxyStyle;
using super::super;
QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc, const QWidget *widget)
const override
{
QRect rect = super::subControlRect(cc, opt, sc, widget);
assert(cc == QStyle::CC_ComboBox);
if (m_positionSource) {
rect = m_positionSource(rect);
}
return rect;
}
void setPositionSource(std::function<QRect(QRect originalRect)> positionSource)
{
m_positionSource = positionSource;
}
private:
std::function<QRect(QRect originalRect)> m_positionSource = nullptr;
};
struct CustomCombobox::Impl {
PositionStyle *style = nullptr;
};
void
CustomCombobox::setDownListPosSource(std::function<QRect(QRect originalRect)> positionSource)
{
if (m_impl && m_impl->style)
m_impl->style->setPositionSource(positionSource);
}
CustomCombobox::CustomCombobox(QWidget *parent) : super(parent), m_impl(new Impl())
{
m_impl->style = new PositionStyle();
setStyle(m_impl->style);
}