利用Qt的QToolBar实现工具栏。这里要注意,工具栏占据的空间仍然属于QWidget,假如程序员调用QPaintEvent来绘制QWidget,工具栏的部分仍然会被画到。因此每次绘制时,要把工具栏占据的区域减掉。
代码:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QToolBar> #include <QAction> #include <QMouseEvent> #include <QPaintEvent> #include <QResizeEvent> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); QToolBar * m_pToolBar; QAction * m_pAct1; QAction * m_pAct2; public slots: void OnClick1(void); void OnClick2(void); protected: void resizeEvent(QResizeEvent *); void paintEvent(QPaintEvent *); }; #endif // MAINWINDOW_H
#include "mainwindow.h" #include <QDebug> #include <QPainter> #include <QIcon> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { m_pAct1 = new QAction(QIcon("E:\\lena.jpg"), "act1", this); m_pAct2 = new QAction(QIcon("E:\\hehe.png"), "act2", this); m_pToolBar = new QToolBar(this); m_pToolBar->addAction(m_pAct1); m_pToolBar->addAction(m_pAct2); addToolBar(Qt::TopToolBarArea, m_pToolBar); QObject::connect(m_pAct1, SIGNAL(triggered()), this, SLOT(OnClick1())); QObject::connect(m_pAct2, SIGNAL(triggered()), this, SLOT(OnClick2())); setMouseTracking(true); } MainWindow::~MainWindow() { delete m_pAct1; delete m_pAct2; delete m_pToolBar; } void MainWindow::OnClick1(void) { qDebug()<<"yello"; } void MainWindow::OnClick2(void) { qDebug()<<"hello"; } void MainWindow::paintEvent(QPaintEvent *e) { QImage img(QString("E:\\lena.jpg")); QPainter qp; qp.begin(this); qp.drawImage(QRectF(0,m_pToolBar->height(), width(), height() - m_pToolBar->height()), img, QRectF(0,0, img.width(), img.height())); qp.end(); } void MainWindow::resizeEvent(QResizeEvent *e) { m_pToolBar->setGeometry(0,0,width(), 50); m_pToolBar->setIconSize(QSize(50,50)); }
效果: