欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

QSharedMemory QBuffer QDataStream 共享内存传输图片 基本控件(十八)

程序员文章站 2022-05-28 11:35:31
...

一、效果图
QSharedMemory QBuffer QDataStream 共享内存传输图片 基本控件(十八)
二、代码

#include "sharedmenory.h"
#include <QSharedMemory>
#include <QPixmap>
#include <QCoreApplication>
#include <QDir>
#include <QBuffer>
#include <QDataStream>
#include <QDebug>
sharedMenory::sharedMenory()
{
    create();
    read();
}

void sharedMenory::create()
{
    QPixmap pixmap;
    pixmap.load(QCoreApplication::applicationDirPath() + QDir::separator() + "1.jpg");

    QBuffer buffer;
    buffer.open(QIODevice::ReadWrite);

    QDataStream out(&buffer);
    out<<pixmap;

    int buffer_size = buffer.size();

    QSharedMemory *pSharedMen = new QSharedMemory("key-img",this);
    bool ret = pSharedMen->create(buffer_size);
    int shareMen_size = pSharedMen->size();

    if(!ret){
        qDebug()<<pSharedMen->errorString();
        return;
    }

    pSharedMen->lock();
    char* to = static_cast<char*>(pSharedMen->data());
    const char* from = buffer.data().constData();
    memcpy(to,from,qMin(buffer_size,shareMen_size));
    pSharedMen->unlock();
}

void sharedMenory::read()
{
    QBuffer buffer;
    QDataStream in(&buffer);
    QPixmap pixmap;

    QSharedMemory *pSharedMen = new QSharedMemory("key-img",this);
    qDebug()<<pSharedMen->isAttached();
    if(pSharedMen->isAttached() == false)
        pSharedMen->attach();
    pSharedMen->lock();
    buffer.setData(static_cast<const char*>(pSharedMen->constData()),pSharedMen->size());
    buffer.open(QBuffer::ReadWrite);
    in>>pixmap;
    pSharedMen->unlock();
    pSharedMen->detach();

    QWidget *w = new QWidget;
    w->resize(400,400);
    w->show();
    QLabel *label = new QLabel(w);
    label->resize(400,400);
    label->setPixmap(pixmap);
    label->show();
}

相关标签: # Qt-基本控件