我将插槽连接到QClipboard的dataChanged信号,以将剪贴板中的图像存储到变量mimedata(reference):
void MyWin::clipboardDataChanged()
{
const QMimeData * m=QApplication::clipboard()->mimeData();
mimedata = new QMimeData();
foreach(QString format, m->formats())
{
QByteArray data = m->data(format);
if(format.startsWith("application/x-qt"))
{
int index1 = format.indexOf('"') + 1;
int index2 = format.indexOf('"', index1);
format = format.mid(index1, index2 - index1);
}
mimedata->setData(format, data);
}
}
并将mimedata还原到剪贴板,如下所示:
void MyWin::onrestore()
{
QApplication::clipboard()->setMimeData(mimedata);
}
但是,剪贴板中设置的数据似乎已损坏。如果我从剪贴板粘贴到Paint,它会显示“剪贴板上的信息无法插入Paint”。我在剪贴板中打印了数据格式,即“ application / x-qt-image”。因此,我认为这不是其他应用程序支持的格式。这是Qt的错误还是代码有缺陷?
void MyWin::clipboardDataChanged()
{
const QMimeData * m = QApplication::clipboard()->mimeData();
mimedata = new QMimeData();
for(auto format : m->formats())
{
mimedata->setData(format, m->data(format));
}
}
或者,将application/x-qt-image
数据转换为QImage
,然后使用QMimeData::setImageData
进行存储:
void Widget::clipboardDataChanged() { const QMimeData * m = QApplication::clipboard()->mimeData(); mimedata = new QMimeData(); for(auto format : m->formats()) { if(format == "application/x-qt-image") { QImage image; QByteArray data = m->data(format); QBuffer buffer(&data); image.load(&buffer, nullptr); mimedata->setImageData(image); } } }