UI: MenuWidget: Relayout on child add/remove too

This commit is contained in:
Nodir Temirkhodjaev 2023-12-24 17:26:14 +03:00
parent 379786cf1b
commit 4995cb3b3b
4 changed files with 29 additions and 21 deletions

View File

@ -1,9 +1,7 @@
#include "controlutil.h"
#include <QActionEvent>
#include <QBoxLayout>
#include <QCheckBox>
#include <QCoreApplication>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
@ -176,29 +174,17 @@ QMenu *ControlUtil::createMenu(QWidget *parent)
QMenu *ControlUtil::createMenuByLayout(QBoxLayout *layout, QWidget *parent)
{
auto menu = createMenu(parent);
auto wa = new QWidgetAction(menu);
auto menuWidget = new MenuWidget();
auto menuWidget = new MenuWidget(menu, wa);
menuWidget->setLayout(layout);
auto wa = new QWidgetAction(menu);
wa->setDefaultWidget(menuWidget);
menu->addAction(wa);
menu->connect(menuWidget, &MenuWidget::layoutRequested, [=] { relayoutMenu(menu, wa); });
return menu;
}
void ControlUtil::relayoutMenu(QMenu *menu, QAction *action)
{
if (!action) {
action = menu->actions().first();
}
QActionEvent e(QEvent::ActionChanged, action);
QCoreApplication::sendEvent(menu, &e);
}
QBoxLayout *ControlUtil::createLayoutByWidgets(const QList<QWidget *> &widgets, Qt::Orientation o)
{
auto layout =

View File

@ -59,7 +59,6 @@ public:
static QMenu *createMenu(QWidget *parent = nullptr);
static QMenu *createMenuByLayout(QBoxLayout *layout, QWidget *parent);
static void relayoutMenu(QMenu *menu, QAction *action = nullptr);
static QBoxLayout *createLayoutByWidgets(
const QList<QWidget *> &widgets, Qt::Orientation o = Qt::Vertical);

View File

@ -1,8 +1,16 @@
#include "menuwidget.h"
#include <QActionEvent>
#include <QCoreApplication>
#include <QEvent>
#include <QMenu>
MenuWidget::MenuWidget(QWidget *parent) : QWidget(parent) { }
MenuWidget::MenuWidget(QMenu *menu, QAction *action, QWidget *parent) :
QWidget(parent), m_menu(menu), m_action(action)
{
connect(this, &MenuWidget::layoutChanged, this, &MenuWidget::relayoutMenu,
Qt::ConnectionType(Qt::QueuedConnection | Qt::UniqueConnection));
}
bool MenuWidget::event(QEvent *event)
{
@ -10,8 +18,10 @@ bool MenuWidget::event(QEvent *event)
const bool res = QWidget::event(event);
switch (type) {
case QEvent::ChildAdded:
case QEvent::ChildRemoved:
case QEvent::LayoutRequest: {
emit layoutRequested();
emit layoutChanged();
} break;
default:
break;
@ -19,3 +29,9 @@ bool MenuWidget::event(QEvent *event)
return res;
}
void MenuWidget::relayoutMenu()
{
QActionEvent e(QEvent::ActionChanged, m_action);
QCoreApplication::sendEvent(m_menu, &e);
}

View File

@ -8,13 +8,20 @@ class MenuWidget : public QWidget
Q_OBJECT
public:
explicit MenuWidget(QWidget *parent = nullptr);
explicit MenuWidget(QMenu *menu, QAction *action, QWidget *parent = nullptr);
signals:
void layoutRequested();
void layoutChanged();
protected:
bool event(QEvent *event) override;
private:
void relayoutMenu();
private:
QMenu *m_menu = nullptr;
QAction *m_action = nullptr;
};
#endif // MENUWIDGET_H