Qt点击按钮在其附近弹出一个窗口

发布时间:2024年01月12日

效果

在这里插入图片描述

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_OBJECT

public:
    FS_PopupWidget(QWidget *parent = Q_NULLPTR);
    ~FS_PopupWidget();

private:
    QPointer<QWidgetAction> m_popup_widget;
    QPointer<QMenu> m_menu;
};
#endif // FS_POPUPWIDGET_H

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)
{
    // set ToolButton attribute
    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;
}


文章来源:https://blog.csdn.net/weixin_42797483/article/details/135551427
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。