QT Creator在Designer模式使用QToolButton

QT Creator模式下,可以在工具条上,从下面拉Action到工具条上。其实,这时候工具条上的icon就是QToolButton。很多时候,我们需要在这个toolbar上增加下拉菜单,就是在icon右侧增加一个下拉菜单的功能。

我看了下,网上几乎都是自己定义菜单、自己定义QToolButton,然后人工代码里添加。这个和可视化的QT Creator是背道而驰的。有没有什么办法在QT Designer里面就可以处理呢?其实是可以的

qtcentre.org 里写道

Create an action and add it to your tool bar. The QToolButton will be created automagically by the QToolBar.

Check out the action editor in Qt designer. If you use that to create a new action, you can drag the action into the tool bar.

我们可以用QToolbar::widgetForAction 这个函数得到相关的QWidget指针,动态转换到 QToolButton就可以了。然后增加 setToolButtonStyle    setPopupMode   setMenu来处理即可。

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QToolButton>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QToolButton * pTbBtn = dynamic_cast<QToolButton *> (ui->mainToolBar->widgetForAction(ui->action_6));
//    pTbBtn->setToolButtonStyle(Qt::ToolButtonIconOnly);
    pTbBtn->setPopupMode(QToolButton::MenuButtonPopup);
//    pTbBtn->setArrowType(Qt::LeftArrow);
//    pTbBtn->setText("Left Arrow");
    // 文本位于图标之下
//    pTbBtn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    //pTbBtn->setStyleSheet("QToolButton{border: none; background: rgb(68, 69, 73); color: rgb(0, 160, 230);}");
}
MainWindow::~MainWindow()
{
    delete ui;   
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值