一般控件,滚轮默认滚动垂直滚动条,比如表格、树。我们可以通过重写滚轮事件来控制滚动方向(水平:shift+wheel 垂直:wheel)。
一、自定义的滚动条QScrollBar
void ScrollW::wheelEvent(QWheelEvent *event)
{
int delta = event->delta();
int m = event->modifiers();
QAbstractSlider::SliderAction act;
if (delta < 0)
act = QAbstractSlider::SliderSingleStepAdd;
else
act = QAbstractSlider::SliderSingleStepSub;
if (m == Qt::ShiftModifier)
{
scrollBarH->triggerAction(act);
}
else
{
scrollBarV->triggerAction(act);
}
}
若需要屏蔽掉滚动,直接event->ignore().
二、自带滚动条控件(table/tree)
需要滚轮事件+键盘事件组合
void TableW::wheelEvent(QWheelEvent *event)
{
int delta = event->delta();
int m = event->modifiers();
if (m == Qt::ShiftModifier)
{
QAbstractSlider::SliderAction act;
if (delta < 0)
{
act = QAbstractSlider::SliderSingleStepAdd;
}
else
{
act = QAbstractSlider::SliderSingleStepSub;
}
m_table->horizontalScrollBar()->triggerAction(act);
}
}
void TableW::keyPressEvent(QKeyEvent *event)
{
int m = event->modifiers();
if ((m == Qt::ShiftModifier))
{
m_table->verticalScrollBar()->setDisabled(true);
}
TableParW::keyPressEvent(event); //父处理
}
void TableW::keyReleaseEvent(QKeyEvent *event)
{
m_table->verticalScrollBar()->setDisabled(false);
TableParW::keyReleaseEvent(event);
}