关键代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QToolBar>
#include <QMessageBox>class QMenuBar;
class QToolBar;
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);QAction* openAction = new QAction("连接",this);openAction->setShortcut(QKeySequence::Open);//动作的快捷键;比如:open快捷键 Ctrl+O(Qt的QKeySequence定义的)openAction->setStatusTip("打开文件");//添加状态栏的提示语句openAction->setIcon(QIcon(":/res/break-link.jpg"));//添加这句代码,添加图标auto file = menuBar()->addMenu("菜单栏");file->addAction(openAction);QToolBar* toolBar = addToolBar("工具栏");QWidget *spacer = new QWidget(this);spacer->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);toolBar->addWidget(spacer);// 此种方式为文字显示在图标下面,如图所示toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);toolBar->setIconSize(QSize(40,50));toolBar->addAction(openAction);connect(openAction,SIGNAL(triggered()),this,SLOT(link()));QAction* svg = new QAction("首页",this);svg->setShortcut(QKeySequence::Back);svg->setStatusTip("首页");svg->setIcon(QIcon(QPixmap(":/res/icon-home page.svg")));//添加这句代码,添加图标toolBar->addAction(svg);toolBar->setMovable(false);connect(svg,SIGNAL(triggered()),this,SLOT(homePage()));pixmap = new QPixmap (":/res/bg.png");
}void MainWindow::homePage() {QMessageBox::information(this,"提示","点击首页");
}
void MainWindow::link() {QMessageBox::information(this,"提示","点击连接");
}void MainWindow::setBg() {qDebug()<<"重置窗口大小";QPalette palette;palette.setBrush(backgroundRole(), QBrush(*pixmap));setPalette(palette);palette.setBrush(QPalette::Window,QBrush(pixmap->scaled(this->size(), Qt::IgnoreAspectRatio,Qt::SmoothTransformation)));setPalette(palette);
}void MainWindow::resizeEvent(QResizeEvent *event) {setBg();
}MainWindow::~MainWindow()
{delete ui;delete pixmap;
}
效果
完整代码示例
https://download.csdn.net/download/qq_44575789/85394829