QHeaderView禁用某些列的排序,则只需要重载mousePressEvent mouseReleaseEvent两个函数,在函数体内判断当前点击列是否为需要禁用的列,如果是则设置点击无效setSectionsClickable(false); 再调用QHeaderView::mousePressEvent(event);/QHeaderView::mouseReleaseEvent(event); 然后再setSectionsClickable(true);
代码如下:
void HanderView::mousePressEvent(QMouseEvent* event)
{
const int index = logicalIndexAt(event->pos());
if (0 <= m_forbinSortList.indexOf(index))
{
setSectionsClickable(false);
}
QHeaderView::mousePressEvent(event);
if (!sectionsClickable())
{
setSectionsClickable(true);
}
}
void HanderView::mouseReleaseEvent(QMouseEvent* event)
{
const int index = logicalIndexAt(event->pos());
if (0 <= m_forbinSortList.indexOf(index))
{
setSectionsClickable(false);
}
QHeaderView::mouseReleaseEvent(event);
if (!sectionsClickable())
{
setSectionsClickable(true);
}
}
添加QCheckBox:
HanderView::HanderView(Qt::Orientation orientation, QWidget *parent)
: QHeaderView(orientation, parent)
{
m_pCheckBox = new QCheckBox(this);
m_pCheckBox->setFixedSize(qRound(1.3 * m_pCheckBox->sizeHint().height()),
m_pCheckBox->sizeHint().height());
m_pCheckBox->setFocusPolicy(Qt::NoFocus);
}
void HanderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const
{
if (0 == logicalIndex)
{
int iYOffset = m_pCheckBox->height() < rect.height()
? (rect.height() - m_pCheckBox->height()) /2 : 0;
QRect rectCheckBox(rect.x() + 3, rect.y() + iYOffset,
m_pCheckBox->width(), m_pCheckBox->height());
m_pCheckBox->setGeometry(rectCheckBox);
}
QHeaderView::paintSection(painter, rect, logicalIndex);
}
header()->setStyleSheet("\
QHeaderView::section {\
background-color:#f2f2f2;\
padding-left: 1px;\
border-left: 0;\
border-right: 0;\
border-top: 1px solid #cdd4df;\
border-bottom: 0;\
height: 25px;}\
QHeaderView::section:first{\
padding: 0px 0px 0px 22px;}\
QHeaderView::up-arrow{\
subcontrol-origin: padding;\
subcontrol-position: right;\
width: 15px; padding-right: 20px;}\
QHeaderView::down-arrow{\
subcontrol-origin: padding;\
subcontrol-position: right;\
width: 15px; padding-right: 20px;\
}");