效果
FS_PopupWidget.h
#ifndef FS_POPUPWIDGET_H
#define FS_POPUPWIDGET_H#pragma once#include <QToolButton>
#include <QWidgetAction>
#include <QPointer>class QMenu;class FS_PopupWidget : public QToolButton
{Q_OBJECTpublic:FS_PopupWidget(QWidget *parent = Q_NULLPTR);~FS_PopupWidget();private:QPointer<QWidgetAction> m_popup_widget;QPointer<QMenu> m_menu;
};
#endif
FS_PopupWidget.cpp
#include"fs_popupwidget.h"#include <QMenu>
#include <QListWidget>
#include <QListWidgetItem>
#include <QHBoxLayout>
#include <QVBoxLayout>#pragma execution_character_set("utf-8")FS_PopupWidget::FS_PopupWidget(QWidget *parent): QToolButton(parent)
{this->setPopupMode(QToolButton::InstantPopup);this->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);this->setIcon(QIcon(":/images/images/error.png"));this->setText("弹出");m_popup_widget = new QWidgetAction(this);m_menu = new QMenu(this);QPointer<QListWidget> lwd = new QListWidget;lwd->setMinimumSize(QSize(400, 400));lwd->setViewMode(QListView::IconMode);lwd->setIconSize(QSize(80, 80));for (int i = 0; i < 10; i++){QListWidgetItem* item = new QListWidgetItem(QIcon(":/images/images/warning.png"), "Test");lwd->addItem(item);}QPointer<QVBoxLayout> layout_main = new QVBoxLayout;layout_main->addWidget(lwd);QPointer<QWidget> default_widget = new QWidget;default_widget->setLayout(layout_main);m_popup_widget->setDefaultWidget(default_widget);m_menu->addAction(m_popup_widget);this->setMenu(m_menu);
}FS_PopupWidget::~FS_PopupWidget()
{
}
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"QHBoxLayout"
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);myFS_PopupWidget=new FS_PopupWidget();ui->verticalLayout->addWidget(myFS_PopupWidget);
}MainWindow::~MainWindow()
{delete ui;
}