Qt QComboBox向右展开的方法

写项目的时候需要设计一个向右展开的一个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.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值