写项目的时候需要设计一个向右展开的一个widget,其实也可以用点击按钮show出widget,但是这个widget的位置正好位于一个大view上面,不在QPushButton所在的widget,所以如果按照这个方法的话究极麻烦,看了网上许许多多的方法,都不咋地,最终东拼西凑终于写出来了。。但是领导不给合并,说是阿巴阿巴阿巴。。然后让我用我所说的第一种麻烦的方法,我直接无语了,唉,最终可能妥协,代码写在这里保存起来吧。
1. 重构造函数设置一些东西
AQPopRightComboBox::AQPopRightComboBox(QWidget* parent) :QComboBox(parent)
{
this->setObjectName("bottom_arrow_combobox");
QListView* view = new QListView();
view->installEventFilter(this);//这个是必须的
this->setView(view);
}
2. 重写showup()
void AQPopRightComboBox::showPopup()
{
bool oldAnimationEffects = qApp->isEffectEnabled(Qt::UI_AnimateCombo);
//这个关闭popup的弹出,否则会出现popup移动的动画闪现,不太美观
qApp->setEffectEnabled(Qt::UI_AnimateCombo, false);
QComboBox::showPopup();
//然后按照本来央视设置状态
qApp->setEffectEnabled(Qt::UI_AnimateCombo, oldAnimationEffects);
}
3. 重写eventFilter()
bool AQPopRightComboBox::eventFilter(QObject* o, QEvent* e)
{
if (e->type() == QEvent::Show && o == view()) {
QWidget* popup = this->findChild<QFrame*>();
//将popup移到右边
popup->move(popup->x() + this->width(), popup->y() - this->height());
popup->setFixedWidth(160);
}
return QComboBox::eventFilter(o, e);
}
4. 重写paintEvent()
void AQPopRightComboBox::paintEvent(QPaintEvent*)
{
QStylePainter painter(this);
painter.setPen(palette().color(QPalette::Text));
QStyleOptionComboBox opt;
initStyleOption(&opt);
painter.drawComplexControl(QStyle::CC_ComboBox, opt);
if (opt.editable){
painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
else{
QRect text_rect_all = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxArrow, this);
//spinbox的文字显示的位置
QRect text_rect_noarrow = QRect(text_rect_all.left(), text_rect_all.top() + 5, text_rect_all.width(), text_rect_all.height() - 21);
QStyleOptionButton optLabel;
optLabel.init(this);
optLabel.rect = text_rect_noarrow;
//文字显示的方向
optLabel.text = opt.currentText.split("", QString::SkipEmptyParts).join("\n");
optLabel.icon = opt.currentIcon;
optLabel.iconSize = opt.iconSize;
painter.drawControl(QStyle::CE_PushButtonLabel, optLabel);
}
}
5. qss设置箭头样式
QComboBox#bottom_arrow_combobox::drop-down{
subcontrol-position: center bottom;
}
QComboBox#bottom_arrow_combobox::down-arrow{
subcontrol-position: center bottom;
image: url(:/images/ui/spinbox_right_arrow.png);
}
QComboBox#bottom_arrow_combobox::down-arrow:on{
subcontrol-position: center bottom;
image: url(:/images/ui/spinbox_left_arrow.png);
}
over.