Reputation: 986
I connect a slot to the dataChanged signal of QClipboard to store the image in the clipboard to a variable 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);
}
}
And restore mimedata to clipboard as follows:
void MyWin::onrestore()
{
QApplication::clipboard()->setMimeData(mimedata);
}
However, the data set to the clipboard seems corrupted. If I paste from the clipboard to Paint, it says "The information on the Clipboard can't be inserted into Paint." I printed the format of the data in the clipboard, i.e., "application/x-qt-image". So I think it is not a format that is supported by other applications. Is this a bug of Qt or the code is flawed?
Upvotes: 1
Views: 710
Reputation: 10057
I think you'd be better save the whole clipboard content, so you can safely restore it when needed, i.e.
void MyWin::clipboardDataChanged()
{
const QMimeData * m = QApplication::clipboard()->mimeData();
mimedata = new QMimeData();
for(auto format : m->formats())
{
mimedata->setData(format, m->data(format));
}
}
Alternatively, convert the application/x-qt-image
data into a QImage
, then use QMimeData::setImageData
to store it:
void MyWin::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);
}
}
}
Upvotes: 2