xviewer.h
#pragma once
#include <QtWidgets/QWidget>
#include "ui_xviewer.h"
#include <QMenu>
class XViewer : public QWidget
{
Q_OBJECT
public:
XViewer(QWidget* parent = Q_NULLPTR);
//右键菜单
void contextMenuEvent(QContextMenuEvent* event) override;
void View(int count);
public slots:
void View1();
void View4();
void View9();
void View16();
private:
Ui::XViewerClass ui;
QMenu left_menu_;
};
xviewer.cpp
#include "xviewer.h"
#include <QMouseEvent>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QResizeEvent>
#include <QDebug>
#include <QContextMenuEvent>
#include <QGridLayout>
//解决中文乱码
#define C(s) QString::fromLocal8Bit(s)
//一个指针数组,里面存了16个指向wgehit的指针
//cam_wids表示这16个指针的总大小 ,如果全为空则 cam_wids = 0,如果有两个不空,则cam_wids = 2 * //sizeof(QWidget*)这么大
static QWidget* cam_wids[16] = { 0 };
XViewer::XViewer(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
//
/// 初始化右键菜单
// 视图=》 1 窗口
// 4 窗口
auto m = left_menu_.addMenu(C("视图"));
auto a = m->addAction(C("1窗口"));
connect(a, SIGNAL(triggered()), this, SLOT(View1()));
a = m->addAction(C("4窗口"));
connect(a, SIGNAL(triggered()), this, SLOT(View4()));
a = m->addAction(C("9窗口"));
connect(a, SIGNAL(triggered()), this, SLOT(View9()));
a = m->addAction(C("16窗口"));
connect(a, SIGNAL(triggered()), this, SLOT(View16()));
//默认九窗口
View9();
}
void XViewer::View1()
{
View(1);
}
void XViewer::View4()
{
View(4);
}
void XViewer::View9()
{
View(9);
}
void XViewer::View16()
{
View(16);
}
void XViewer::View(int count)
{
qDebug() << "View" << count;
// 2X2 3X3 4X4
//确定列数 根号
int cols = sqrt(count);
//总窗口数量,和count区分,表示当前仅显示的数量
int wid_size = sizeof(cam_wids) / sizeof(QWidget*);
//初始化布局器
auto lay = (QGridLayout*)ui.cams->layout();//当前布局转为网格布局
if (!lay)//如果没有布局则重新创建一个网格布局
{
lay = new QGridLayout();
lay->setContentsMargins(0, 0, 0, 0);
lay->setSpacing(2);//元素间距
ui.cams->setLayout(lay);//创建网格布局
}
//初始化窗口
for (int i = 0; i < count; i++)
{
if (!cam_wids[i])
{
cam_wids[i] = new QWidget();
cam_wids[i]->setStyleSheet("background-color:rgb(51,51,51);");
}
lay->addWidget(cam_wids[i], i / cols, i % cols);
}
//清理多余的窗体
for (int i = count; i < wid_size; i++)
{
if (cam_wids[i])
{
delete cam_wids[i];
cam_wids[i] = nullptr;
}
}
}
void XViewer::contextMenuEvent(QContextMenuEvent* event)
{
//鼠标位置显示右键菜单
left_menu_.exec(QCursor::pos());
event->accept();
}
/
/// 鼠标拖动窗口
static bool mouse_press = false;
static QPoint mouse_point;//鼠标的坐标
void XViewer::mouseMoveEvent(QMouseEvent* ev)
{
if (!mouse_press)
{
QWidget::mouseMoveEvent(ev);
return;
}
this->move(ev->globalPos() - mouse_point);//鼠标在移动的过程中执行
}
void XViewer::mousePressEvent(QMouseEvent* ev)
{
if (ev->button() == Qt::LeftButton)
{
mouse_press = true;
mouse_point = ev->pos();
}
}
void XViewer::mouseReleaseEvent(QMouseEvent* ev)
{
mouse_press = false;
}