一、常用数据类型
QClipboard类提供了对操作系统剪切板的操作接口,最常用的做法是复制粘贴文本,如下面示例
QClipboard *clipboard = QGuiApplication::clipboard();
QString originalText = clipboard->text(); //获得剪切板中的文本(粘贴)
...
clipboard->setText(newText); //往剪切板里写文本(复制)
QClipboard 提供了几组函数用来访问常见的数据类型,如果我们想操作的数据类型是QString、QImage或QPixmap,可以直接使用这些接口。
QImage image(QClipboard::Mode mode = Clipboard) const
void setImage(const QImage &image, QClipboard::Mode mode = Clipboard)
QPixmap pixmap(QClipboard::Mode mode = Clipboard) const
void setPixmap(const QPixmap &pixmap, QClipboard::Mode mode = Clipboard)
QString text(QClipboard::Mode mode = Clipboard) const
QString text(QString &subtype, QClipboard::Mode mode = Clipboard) const
void setText(const QString &text, QClipboard::Mode mode = Clipboard)
二、自定义数据类型
如果想将自定义的数据类型写进系统剪切板,并可以从系统剪切板读到我们写进去的自定义的数据类型,可以使用QMimeData+QDataStream。下面举一个简单示例。
#include <QApplication>
#include <QPushButton>
#include <QClipboard>
#include <QMimeData>
#include <QDebug>
struct Device
{
int index;
QString text;
};
void setDeviceToClipboard(struct Device &d)
{
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
dataStream << d.index;
dataStream << d.text;
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/itemdata", itemData);
QClipboard *clipboard = QApplication::clipboard();
clipboard->setMimeData(mimeData);
}
struct Device *getDeviceFromClipboard()
{
const QClipboard *clipboard = QApplication::clipboard();
const QMimeData *mimeData = clipboard->mimeData();
if (mimeData->hasFormat("application/itemdata"))
{
QByteArray itemData = mimeData->data("application/itemdata");
QDataStream dataStream(&itemData, QIODevice::ReadOnly);
struct Device *pDevice = new struct Device;
dataStream >> pDevice->index;
dataStream >> pDevice->text;
return pDevice;
}
return nullptr;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
struct Device d1;
d1.index = 1;
d1.text = "device1";
//往剪切板写自定义数据
setDeviceToClipboard(d1);
//从剪切板读自定义数据
struct Device *pDevice = getDeviceFromClipboard();
if (pDevice != nullptr)
{
qDebug() << pDevice->index;
qDebug() << pDevice->text;
}
return 0;
}