效果

MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include"toollayout.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private:Ui::MainWindow *ui;QAction *actionIpSet;QAction *actionAuthorize;ToolLayout *myToolLayout;
private slots:void slot_action_triggered(QAction *action);
};
#endif
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"QHBoxLayout"
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);myToolLayout=new ToolLayout();QHBoxLayout *qHbox=new QHBoxLayout();qHbox->addWidget(myToolLayout);qHbox->addWidget(ui->pushButton_4);QMenu* menu = new QMenu(this);actionIpSet = new QAction("按钮1", this);actionAuthorize = new QAction("按钮2", this);menu->addAction(actionIpSet);menu->addAction(actionAuthorize);menu->addSeparator();menu->setWindowFlags(menu->windowFlags() | Qt::FramelessWindowHint);menu->setAttribute(Qt::WA_TranslucentBackground);ui->pushButton_4->setMenu(menu);centralWidget()->setLayout(qHbox);connect(menu, &QMenu::triggered, this, &MainWindow::slot_action_triggered);
}MainWindow::~MainWindow()
{delete ui;
}
void MainWindow::slot_action_triggered(QAction *action)
{if(action == actionIpSet){}else if(action == actionAuthorize){}
}
ToolLayout.h
#ifndef TOOLLAYOUT_H
#define TOOLLAYOUT_H#include <QWidget>
#include"QAction"
#include"QMenu"
namespace Ui {
class ToolLayout;
}class ToolLayout : public QWidget
{Q_OBJECTpublic:explicit ToolLayout(QWidget *parent = nullptr);~ToolLayout();private:Ui::ToolLayout *ui;QAction *actionIpSet;QAction *actionAuthorize;
private slots:void slot_action_triggered(QAction *action);
};#endif
ToolLayout.cpp
#include "toollayout.h"
#include "ui_toollayout.h"
#include"QMessageBox"
ToolLayout::ToolLayout(QWidget *parent) :QWidget(parent),ui(new Ui::ToolLayout)
{ui->setupUi(this);ui->label_2->setAlignment(Qt::AlignCenter);ui->label_3->setAlignment(Qt::AlignCenter);ui->label_4->setAlignment(Qt::AlignCenter);QMenu* menu = new QMenu(this);actionIpSet = new QAction("actionIpSet", this);actionAuthorize = new QAction("actionAuthorize", this);menu->addAction(actionIpSet);menu->addAction(actionAuthorize);menu->addSeparator();menu->setWindowFlags(menu->windowFlags() | Qt::FramelessWindowHint);
ui->pushButton->setMenu(menu);
connect(menu, &QMenu::triggered, this, &ToolLayout::slot_action_triggered);
}ToolLayout::~ToolLayout()
{delete ui;
}
void ToolLayout::slot_action_triggered(QAction *action)
{if(action == actionIpSet){QMessageBox::information(this,u8"INFO",u8"actionIpSet");}else if(action == actionAuthorize){QMessageBox::information(this,u8"INFO",u8"actionAuthorize");}
}