当你需要制作一个工具栏上的按钮时,就需要用到toolButton,那我们该如何做呢?
1、首先你需要在头文件内引入两个类QToolBar、QToolButton
#include <QToolBar> //引入QToolBar类
#include <QToolButton> //引入QToolButton类
2、然后你需要定义一个工具栏的对象 ,定义一个工具栏内的按钮
private:
QToolBar *tbar;
QToolButton *tbutton1,*tbutton2;
3、设置窗口大小、工具栏实例化+设置大小
this->setGeometry(300,300,500,300);//前面两个是在屏幕的位置,后面两个的窗口的长和宽
tbar = new QToolBar(this);
tbar->setGeometry(20,20,1000,200);
4、引入一个图标,这个图标是系统自带的
//将QStyle类对象进行实例化,主要目的设置风格,图标是系统自带
QStyle *sty=QApplication::style();
QIcon ico = sty->standardIcon(QStyle::SP_TitleBarCloseButton);
QIcon ico1 = sty->standardIcon(QStyle::SP_TitleBarContextHelpButton);
5、实例化按钮,设置按钮大小和位置,将上述图标给按钮,还有名称
//将QToolButton对象进行实例化
tbutton1 = new QToolButton();
tbutton2 = new QToolButton();
tbutton1->setGeometry(20,20,90,50);
tbutton2->setGeometry(90,20,90,50);
tbutton2->setIcon(ico);
tbutton1->setIcon(ico1);
tbutton2->setText("退出");
tbutton1->setText("系统帮助提示");//设置将要显示文本
6、设置图标的位置,将按钮加到工具栏内
//调用setToolButtonStyle函数设置tbutton样式,设置文本在图标下方
tbutton2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
tbutton1->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
tbar->addWidget(tbutton1);
tbar->addWidget(tbutton2);