От: | Мёртвый Даун | ||
Дата: | 05.07.21 17:25 | ||
Оценка: |
When a toolbar is resized in such a way that it is too small to
show all the items it contains, an extension button will appear as
the last item in the toolbar. Pressing the extension button will
pop up a menu containing the items that do not currently fit in
the toolbar.
When a QToolBar is not a child of a QMainWindow, it loses the ability
to populate the extension pop up with widgets added to the toolbar using
addWidget(). Please use widget actions created by inheriting QWidgetAction
and implementing QWidgetAction::createWidget() instead.
class MyWidget : public QWidget {
...
}
class MyWidgetAction : public QWidgetAction {
Q_OBJECT
public:
MyWidgetAction(QObject *parent) : QWidgetAction(parent) {}
protected:
QWidget *createWidget(QWidget *parent) {
auto *widget = new MyWidget();
// создали наш виджет, настроили, этот метод потом будет вызван в тулбаре при добавлении action'а.
return widget;
}
void deleteWidget(QWidget *widget) { QWidgetAction::deleteWidget(widget); }
};
class MyWidgetAction : public QWidgetAction {
Q_OBJECT
public:
explicit MyWidgetAction(QWidget *widget, QObject *parent) : QWidgetAction(parent), widget_(widget) {}
~MyWidgetAction() Q_DECL_OVERRIDE { widget_->setParent(Q_NULLPTR); }
QWidget *createWidget(QWidget *parent) Q_DECL_OVERRIDE {
// widget это всего лишь контейнер для нашего виджета, чтобы положить его на тулбар
QFrame *widget = new QFrame(parent);
widget->setMinimumHeight(32);
//widget_->setParent(widget); // ???
auto layout = new QHBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(widget_.data());
widget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);
widget->setLayout(layout);
widget->show();
widget_->show();
widget->update();
return widget;
}
void deleteWidget(QWidget *widget) Q_DECL_OVERRIDE {
// Виджет-контейнер тут потом удалится, а наш виджет где-то там потом сам удалится
widget_->hide();
widget->layout()->removeWidget(widget_.data());
widget_->setParent(Q_NULLPTR);
QWidgetAction::deleteWidget(widget);
}
private:
const QScopedPointer<QWidget, QScopedPointerDeleteLater> widget_; // указатель на наш уже созданный виджет где-то за пределами
};
// Используем
// Где-то создали наш виджет, настроили его, еще чота поделали
auto *myWidget = new MyWidget(toolBar);
...
// и добавляем его на тулбар
toolBar->addAction(new MyWidgetAction(myWidget, toolBar));