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;   
}


猜你喜欢

转载自blog.csdn.net/stevenkoh/article/details/79220039
今日推荐