代码编译为release文件,所有依赖文件执行打包,生成可独立运行的程序,这样程序可以重复打开。
程序打开两次,第一个程序点第一个按钮,第二个程序点第二个按钮


- #ifndef DIALOG_H
- #define DIALOG_H
-
- #include
- #include
//采用共享内存方式实现进程间通信 -
- QT_BEGIN_NAMESPACE
- namespace Ui { class Dialog; }
- QT_END_NAMESPACE
-
- class Dialog : public QDialog
- {
- Q_OBJECT
-
- public:
- Dialog(QWidget *parent = nullptr);
- ~Dialog();
- public slots:
- void LoadFromFile();
- void LoadFromSharedMemory();
-
- private slots:
- void on_pushButton_loadFromFile_clicked();
-
- void on_pushButton_loadFromSharedMemory_clicked();
-
- private:
- Ui::Dialog *ui;
- void detach();
- QSharedMemory sharedMemo;
- };
- #endif // DIALOG_H
- #include "dialog.h"
- #include "ui_dialog.h"
- //采用共享内存方式实现进程间通信
- #include
- #include
- #include
-
- Dialog::Dialog(QWidget *parent)
- : QDialog(parent)
- , ui(new Ui::Dialog)
- {
- ui->setupUi(this);
- sharedMemo.setKey("QSharedMemoExample");//在使用共享内存以前,需要先为其指定一个key,系统用它来作为底层共享内存段的标识。
- //这个key可以是任意字符串
- }
-
- Dialog::~Dialog()
- {
- delete ui;
- }
- void Dialog::LoadFromFile()
- {
- if(sharedMemo.isAttached())//判断该进程是否连接到了共享内存段
- {
- detach();//进程与共享内存段进行分离
- }
- ui->label->setText(tr("请选择一个图片文件!"));
- QString fileName=QFileDialog::getOpenFileName(0,QString(),QString(),tr("Images(*.png *.jpg)"));
- QImage image;
- if(!image.load(fileName))
- {
- ui->label->setText(tr("选择的文件不是图片文件"));
- return;
- }
- ui->label->setPixmap(QPixmap::fromImage(image));//将图片加载到共享内存
- QBuffer buffer;
- buffer.open(QBuffer::ReadWrite);
- QDataStream out(&buffer);
- out<
//图像放入数据流 - int size=buffer.size();
- if(!sharedMemo.create(size)) //创建共享内容
- {
- ui->label->setText(tr("创建共享内存段失败"));
- return;
- }
- sharedMemo.lock();//保证同一时刻只能有一个进程允许操作共享内存段
- char *to=(char *)sharedMemo.data();
- const char *from=buffer.data().data();
- memcpy(to,from,qMin(sharedMemo.size(),size));//数据段复制到共享内存段。txwtech
- sharedMemo.unlock();
-
- }
- void Dialog::LoadFromSharedMemory()
- {
- if(!sharedMemo.attach())
- {
- ui->label->setText(tr("无法连接到共享内存段。\n请加载一张图片"));
- return;
- }
- QBuffer buffer2;
- QDataStream in2(&buffer2);
- QImage image2;
- sharedMemo.lock();
- buffer2.setData((char *) sharedMemo.constData(),sharedMemo.size());
- buffer2.open(QBuffer::ReadOnly);
- in2>>image2;
- sharedMemo.unlock();
- sharedMemo.detach();
- ui->label->setPixmap(QPixmap::fromImage(image2));
-
- }
- void Dialog::detach()
- {
- if(!sharedMemo.detach())
- {
- ui->label->setText(tr("无法从共享内存中分离"));
- }
- }
-
-
- void Dialog::on_pushButton_loadFromFile_clicked()
- {
- LoadFromFile();
- }
-
- void Dialog::on_pushButton_loadFromSharedMemory_clicked()
- {
- LoadFromSharedMemory();
- }