c – 创建一个调整其内容大小的QDockWidget

我有一个应用程序,其中固定大小的子窗口小部件需要在运行时根据用户输入以编程方式添加到停靠窗口小部件.我想将这些小部件添加到Qt :: RightDockArea上的一个停靠点,从上到下,直到它用完空间,然后创建一个新列并重复(基本上只是流程布局示例
here的反向,我称之为fluidGridLayout)

我可以使用事件过滤器使dock小部件正确调整大小,但调整大小的dock的几何不会改变,并且一些小部件是在主窗口之外绘制的.有趣的是,调整主窗口的大小,或浮动和解开底座会导致它“弹回”到正确的位置(但我无法找到以编程方式复制此窗口的方法)

我无法使用任何内置的QT布局,因为在我的真实程序中使用小部件,它们最终也会被屏幕上移除.

有没有什么方法可以让码头在调整大小后将其左上角坐标更新到正确的位置?

我认为这可能是普遍感兴趣的,因为在QT中获得Dock小部件的直观布局管理行为可能是人类已知的最难的事情.

可见的EXMAPLE:

复制此代码的代码如下所示.

>使用按钮将4个小部件添加到程序中

>调整绿色底部平台的大小,直到只显示两个小部件.请注意,剩余的3个小部件正在主窗口外绘制,但是底座尺寸合适,因为您无法再看到关闭按钮

>取消蓝色停靠小工具.请注意,它适合它的大小.

>将蓝色底座重新对接到右侧底座区域.请注意,它现在似乎表现正常.

>现在将绿色码头的大小调整为最小尺寸.请注意,Dock现在位于GUI的中间位置. WTf,这怎么可能?

代码

下面我给出了从屏幕截图中复制GUI的代码.

main.cpp中:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "QFluidGridLayout.h"
#include "QDockResizeEventFilter.h"
#include <QDockWidget>
#include <QGroupBox>
#include <QPushButton>
#include <QWidget>
#include <QDial>

class QTestWidget : public QGroupBox
{
public:
    QTestWidget() : QGroupBox()
    {
        setFixedSize(50,50);
        setStyleSheet("background-color: red;");

        QDial* dial = new QDial;
        dial->setFixedSize(40,40);
        QLayout* testLayout = new QVBoxLayout;
        testLayout->addWidget(dial);
        //testLayout->setSizeConstraint(QLayout::SetMaximumSize);

        setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
        setLayout(testLayout);
    }

    QSize sizeHint()
    {
        return minimumSize();
    }

    QDial* dial;
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{


    QDockWidget* rightDock = new QDockWidget();
    QDockWidget* bottomDock = new QDockWidget();

    QGroupBox* central = new QGroupBox();
    QGroupBox* widgetHolder = new QGroupBox();
    QGroupBox* placeHolder = new QGroupBox();

    placeHolder->setStyleSheet("background-color: green;");
    placeHolder->setMinimumHeight(50);

    widgetHolder->setStyleSheet("background-color: blue;");
    widgetHolder->setMinimumWidth(50);
    widgetHolder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    widgetHolder->setLayout(new QFluidGridLayout);
    widgetHolder->layout()->addWidget(new QTestWidget);

    QPushButton* addWidgetButton = new QPushButton("Add another widget");
    connect(addWidgetButton, &QPushButton::pressed, [=]()
    {
        widgetHolder->layout()->addWidget(new QTestWidget);
    });

    central->setLayout(new QVBoxLayout());
    central->layout()->addWidget(addWidgetButton);
    rightDock->setWidget(widgetHolder);
    rightDock->installEventFilter(new QDockResizeEventFilter(widgetHolder,dynamic_cast<QFluidGridLayout*>(widgetHolder->layout())));
    bottomDock->setWidget(placeHolder);

    this->addDockWidget(Qt::RightDockWidgetArea, rightDock);
    this->addDockWidget(Qt::BottomDockWidgetArea, bottomDock);

    this->setCentralWidget(central);
    central->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    this->setMinimumSize(500,500);
}

};

QFluidGirdLayout.h

#ifndef QFluidGridLayout_h__
#define QFluidGridLayout_h__

#include <QLayout>
#include <QGridLayout>
#include <QRect>
#include <QStyle>
#include <QWidgetItem>

class QFluidGridLayout : public QLayout
{
public:

    enum    Direction { LeftToRight, TopToBottom};

    QFluidGridLayout(QWidget *parent = 0)
        : QLayout(parent)
    {
        setContentsMargins(8,8,8,8);
        setSizeConstraint(QLayout::SetMinAndMaxSize);
    }

    ~QFluidGridLayout()
    {
        QLayoutItem *item;
        while ((item = takeAt(0)))
            delete item;
    }

    void addItem(QLayoutItem *item)
    {
        itemList.append(item);
    }


    Qt::Orientations expandingDirections() const
    {
        return 0;
    }


    bool hasHeightForWidth() const
    {
        return false;
    }

    int heightForWidth(int width) const
    {
        int height = doLayout(QRect(0, 0, width, 0), true, true);
        return height;
    }

    bool hasWidthForHeight() const
    {
        return true;
    }

    int widthForHeight(int height) const
    {
        int width = doLayout(QRect(0, 0, 0, height), true, false);
        return width;
    }

    int count() const
    {
        return itemList.size();
    }

    QLayoutItem *itemAt(int index) const
    {
        return itemList.value(index);
    }

    QSize minimumSize() const
    {
        QSize size;
        QLayoutItem *item;
        foreach (item, itemList)
            size = size.expandedTo(item->minimumSize());

        size += QSize(2*margin(), 2*margin());
        return size;
    }

    void setGeometry(const QRect &rect)
    {
        QLayout::setGeometry(rect);
        doLayout(rect); 
    }

    QSize sizeHint() const
    {
        return minimumSize();
    }

    QLayoutItem *takeAt(int index)
    {
        if (index >= 0 && index < itemList.size())
            return itemList.takeAt(index);
        else
            return 0;
    }


private:

    int doLayout(const QRect &rect, bool testOnly = false, bool width = false) const
    {
        int left, top, right, bottom;
        getContentsMargins(&left, &top, &right, &bottom);
        QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
        int x = effectiveRect.x();
        int y = effectiveRect.y();
        int lineHeight = 0;
        int lineWidth = 0;

        QLayoutItem* item;
        foreach(item,itemList)
        {
            QWidget* widget = item->widget();   

            if (y + item->sizeHint().height() > effectiveRect.bottom() && lineWidth > 0)
            {
                y = effectiveRect.y();
                x += lineWidth + right;
                lineWidth = 0;
            }

            if (!testOnly)
            {
                item->setGeometry(QRect(QPoint(x, y), item->sizeHint()));
            }


            y += item->sizeHint().height() + top;

            lineHeight = qMax(lineHeight, item->sizeHint().height());
            lineWidth = qMax(lineWidth, item->sizeHint().width());
        }

        if (width)
        {
            return y + lineHeight - rect.y() + bottom;
        }
        else
        {
            return x + lineWidth - rect.x() + right;
        }
    }

    QList<QLayoutItem *> itemList;
    Direction dir;
};

#endif // QFluidGridLayout_h__

QDockResizeEventFilter.h

#ifndef QDockResizeEventFilter_h__
#define QDockResizeEventFilter_h__

#include <QObject>
#include <QLayout>
#include <QEvent>
#include <QDockWidget>
#include <QResizeEvent>

#include "QFluidGridLayout.h"

class QDockResizeEventFilter : public QObject
{
public:

    QDockResizeEventFilter(QWidget* dockChild, QFluidGridLayout* layout, QObject* parent = 0)
        : QObject(parent), m_dockChild(dockChild), m_layout(layout)
    {

    }

protected:

    bool eventFilter(QObject *p_obj, QEvent *p_event)
    {
        if (p_event->type() == QEvent::Resize)
        {
            QResizeEvent* resizeEvent   = static_cast<QResizeEvent*>(p_event);
            QMainWindow* mainWindow     = static_cast<QMainWindow*>(p_obj->parent());       
            QDockWidget* dock           = static_cast<QDockWidget*>(p_obj);

            // determine resize direction
            if (resizeEvent->oldSize().height() != resizeEvent->size().height())
            {
                // vertical expansion
                QSize fixedSize(m_layout->widthForHeight(m_dockChild->size().height()), m_dockChild->size().height());
                if (dock->size().width() != fixedSize.width())
                {
                    m_dockChild->resize(fixedSize);
                    m_dockChild->setFixedWidth(fixedSize.width());
                    dock->setFixedWidth(fixedSize.width());
                    mainWindow->repaint();
                    //dock->setGeometry(mainWindow->rect().right()-fixedSize.width(),dock->geometry().y(),fixedSize.width(), fixedSize.height());
                }
            }
            if (resizeEvent->oldSize().width() != resizeEvent->size().width())
            {
                // horizontal expansion
                m_dockChild->resize(m_layout->sizeHint().width(), m_dockChild->height());
            }

        }

        return false;

    }

private:

    QWidget* m_dockChild;
    QFluidGridLayout* m_layout;

};

#endif // QDockResizeEventFilter_h__

最佳答案 问题是,上面的代码中没有任何内容实际上导致QMainWindowLayout重新计算自身.该函数隐藏在QMainWindowLayout私有类中,但可以通过添加和删除虚拟QDockWidget来激活,这会导致布局无效并重新计算停靠小部件的位置

QDockWidget* dummy = new QDockWidget;
mainWindow->addDockWidget(Qt::TopDockWidgetArea, dummy);
mainWindow->removeDockWidget(dummy);

唯一的问题是,如果你深入研究QT源代码,你会发现添加一个停靠小部件会导致停靠分隔符被释放,这会导致用户试图调整扩展坞大小时出现不直观和不连贯的行为,鼠标竟然’放手’.

void QMainWindowLayout::addDockWidget(Qt::DockWidgetArea area,
                                             QDockWidget *dockwidget,
                                             Qt::Orientation orientation)
{
    addChildWidget(dockwidget);

    // If we are currently moving a separator, then we need to abort the move, since each
    // time we move the mouse layoutState is replaced by savedState modified by the move.
    if (!movingSeparator.isEmpty())
        endSeparatorMove(movingSeparatorPos);

    layoutState.dockAreaLayout.addDockWidget(toDockPos(area), dockwidget, orientation);
    emit dockwidget->dockLocationChanged(area);
    invalidate();
}

这可以通过将光标移回分隔符并模拟鼠标按下来校正,基本上撤消了重新定位底座后的endSeparatorMove calla.发布事件非常重要,而不是发送它,以便在调整大小事件之后发生.这样做的代码如下:

QPoint mousePos = mainWindow->mapFromGlobal(QCursor::pos());
mousePos.setY(dock->rect().bottom()+2);
QCursor::setPos(mainWindow->mapToGlobal(mousePos));
QMouseEvent* grabSeparatorEvent = 
    new QMouseEvent(QMouseEvent::MouseButtonPress,mousePos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);
qApp->postEvent(mainWindow, grabSeparatorEvent);

其中2是占组框边界的幻数.

把它们放在一起,这里是事件过滤器而不是给出所需的行为:

更正了事件过滤器

#ifndef QDockResizeEventFilter_h__
#define QDockResizeEventFilter_h__

#include <QObject>
#include <QLayout>
#include <QEvent>
#include <QDockWidget>
#include <QResizeEvent>
#include <QCoreApplication>
#include <QMouseEvent>

#include "QFluidGridLayout.h"

class QDockResizeEventFilter : public QObject
{

public:
    friend QMainWindow;
    friend QLayoutPrivate;
    QDockResizeEventFilter(QWidget* dockChild, QFluidGridLayout* layout, QObject* parent = 0)
        : QObject(parent), m_dockChild(dockChild), m_layout(layout)
    {

    }

protected:

    bool eventFilter(QObject *p_obj, QEvent *p_event)
    {  
        if (p_event->type() == QEvent::Resize)
        {
            QResizeEvent* resizeEvent   = static_cast<QResizeEvent*>(p_event);
            QMainWindow* mainWindow     = dynamic_cast<QMainWindow*>(p_obj->parent());              
            QDockWidget* dock           = static_cast<QDockWidget*>(p_obj);

            // determine resize direction
            if (resizeEvent->oldSize().height() != resizeEvent->size().height())
            {
                // vertical expansion
                QSize fixedSize(m_layout->widthForHeight(m_dockChild->size().height()), m_dockChild->size().height());
                if (dock->size().width() != fixedSize.width())
                {

                    m_dockChild->setFixedWidth(fixedSize.width());
                    dock->setFixedWidth(fixedSize.width());

                    // cause mainWindow dock layout recalculation
                    QDockWidget* dummy = new QDockWidget;
                    mainWindow->addDockWidget(Qt::TopDockWidgetArea, dummy);
                    mainWindow->removeDockWidget(dummy);

                    // adding dock widgets causes the separator move event to end
                    // restart it by synthesizing a mouse press event
                    QPoint mousePos = mainWindow->mapFromGlobal(QCursor::pos());
                    mousePos.setY(dock->rect().bottom()+2);
                    QCursor::setPos(mainWindow->mapToGlobal(mousePos));
                    QMouseEvent* grabSeparatorEvent = new QMouseEvent(QMouseEvent::MouseButtonPress,mousePos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);
                    qApp->postEvent(mainWindow, grabSeparatorEvent);
                }
            }
            if (resizeEvent->oldSize().width() != resizeEvent->size().width())
            {
                // horizontal expansion
                // ...
            }           
        }   
        return false;
    }

private:

    QWidget* m_dockChild;
    QFluidGridLayout* m_layout;
};

#endif // QDockResizeEventFilter_h__
点赞