QT 分屏功能

一、主要思路
1、自定义一个继承QWidget的类
功能:
实现分屏
实现鼠标左键双击转换分屏状态
2、添加QWidget控件提升到自定义类

二、实现效果
初始状态
QT 分屏功能_第1张图片
双击后
QT 分屏功能_第2张图片
三、主要代码

//鼠标双击事件处理
bool M_WidgetClass::eventFilter(QObject *obj, QEvent *e)
{
    if (e->type() == QEvent::MouseButtonDblClick)
    {
        //获取双击对象
        QLabel* widget = (QLabel*)obj;
        if (!m_widgetFlag)
        {
            m_widgetFlag = true;
            setAllLabelHide();
            m_gridLayout->addWidget(widget, 0, 0);
            widget->setVisible(true);
            widget->setFixedHeight(this->height());
            widget->setFixedWidth(this->width());
            return true;
        }
        else
        {
            m_widgetFlag = false;
            setAllLabelShow();
            return true;
        }
    }
    return false;
}

//添加分屏
void M_WidgetClass::init()
{
    //也可以在这里设置主界面的样式

    //网格布局初始化
    m_gridLayout = new QGridLayout(this);
    m_gridLayout->setContentsMargins(0, 0, 0, 0);

    int height = this->height()/2 - 7;
    int width = this->width()/2 - 7;

    //创建4个分屏
    for(int i = 0 ; i< m_labelNum;i++)
    {
        QLabel *widget = new QLabel(this);
        widget->setFixedHeight(height);
        widget->setFixedWidth(width);

        //加入事件
        widget->installEventFilter(this);
        widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        //加入列表
        m_labelList<<widget;
    }

    //设置布局 两行两列
    m_gridLayout->addWidget(m_labelList.at(0),0,0,1,1);
    m_gridLayout->addWidget(m_labelList.at(1),0,1,1,1);
    m_gridLayout->addWidget(m_labelList.at(2),1,0,1,1);
    m_gridLayout->addWidget(m_labelList.at(3),1,1,1,1);

    this->setLayout(m_gridLayout);
}
void M_WidgetClass::setAllLabelHide()
{
    for (int i = 0; i < m_labelNum; ++i)
    {
        m_gridLayout->removeWidget(m_labelList.at(i));
        m_labelList.at(i)->setVisible(false);
    }
}

void M_WidgetClass::setAllLabelShow()
{
    setAllLabelHide();
    
    for (int i = 0; i < m_labelList.size(); i++)
    {
        m_labelList.at(i)->setVisible(true);
        m_labelList[i]->setFixedHeight(this->height() / 2 - 7);
        m_labelList[i]->setFixedWidth(this->width() / 2 - 7);
        qDebug() << m_labelList.at(i)->width();
    }

    m_gridLayout->addWidget(m_labelList.at(0), 0, 0, 1, 1);
    m_gridLayout->addWidget(m_labelList.at(1), 0, 1, 1, 1);
    m_gridLayout->addWidget(m_labelList.at(2), 1, 0, 1, 1);
    m_gridLayout->addWidget(m_labelList.at(3), 1, 1, 1, 1);
}

void M_WidgetClass::setLabelHeight(int height)
{
    this->setFixedHeight(height);
}

void M_WidgetClass::setLabelWidth(int width)
{
    this->setFixedWidth(width);
}

四、下载链接

你可能感兴趣的:(QT,qt,开发语言,c++)