qt 自定义菜单

时间:2021-05-04 04:20:25
#include "mainwindow.h"
#include <QApplication>
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
 
    return a.exec();
}
 


#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
};
 
#endif // MAINWINDOW_H
 

#include "mainwindow.h"
#include "QMenu"
#include "qwidgetaction.h"
#include "menuitem.h"
#include "QPushButton"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
 
    QMenu* menu = new QMenu(this);
    QWidgetAction* action = new QWidgetAction( this );
    MenuItem* item = new MenuItem();
    action->setDefaultWidget( item );
    menu->addAction( action );
    menu->addAction( "menu 1");
 
 
    QPushButton* btn = new QPushButton( this );
    btn->setMenu( menu );
 
 
 
 
}
 
MainWindow::~MainWindow()
{
 

}

#ifndef MENUITEM_H
#define MENUITEM_H
 
#include <QWidget>
 
class MenuItem : public QWidget
{
public:
    MenuItem(QWidget *parent = 0 );
};
 
#endif // MENUITEM_H


#include "menuitem.h"
#include "QLabel"
#include "QVBoxLayout"
MenuItem::MenuItem(QWidget *parent) :
    QWidget(parent) {
 
    QVBoxLayout* layout = new QVBoxLayout();
 
    QLabel* label1 = new QLabel( "label1" );
    layout->addWidget( label1 );
    QLabel* label2 = new QLabel( "label2" );
    layout->addWidget( label2 );
 
    this->setLayout( layout  );
 
 
}
 



 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


 
 
 
 
菜单默认图标是16, 修改为32


CusIconStyle* m_pCuStyle = new CusIconStyle;
menu.setStyle(m_pCuStyle );

#include "cusiconstyle.h"

CusIconStyle::CusIconStyle()
:QProxyStyle()
{

}
int CusIconStyle::pixelMetric(PixelMetric metric, const QStyleOption * option, const QWidget * widget) const
{
int s = QProxyStyle::pixelMetric(metric, option, widget);
if (metric == QStyle::PM_SmallIconSize) {
s = 32;
}
return s;
}


#ifndef CUSICONSTYLE_H
#define CUSICONSTYLE_H

#include <QProxyStyle>

// set menu item icon from 16*16 to 32*32
class CusIconStyle: public QProxyStyle
{
Q_OBJECT
public:
CusIconStyle();
~CusIconStyle(){}
int pixelMetric(PixelMetric metric, const QStyleOption * option, const QWidget * widget) const;
};

#endif // CUSICONSTYLE_H