The QClipboard class provides reading and writing to the system clipboard.
common use
- Get the text content of the clipboard.
QClipboard *clipboard = QApplication::clipboard();
QString text = clipboard->text();
- Set the text content of the clipboard.
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(newText);
advanced use
- Use the mimeData object of QClipboard to determine the content properties of the clipboard.
- Compared with QClipboard, mimeData can recognize image data, html data, and plain text data.
- Example: (1) Obtain the contents of the system clipboard:
const QClipboard *clipboard = QApplication::clipboard();
const QMimeData *mimeData = clipboard->mimeData();
if (mimeData->hasImage()) {
/* Get clipboard image data*/
QPixmap pixmap = qvariant_cast<QPixmap>(mimeData->imageData());
...
}
else if (mimeData->hasHtml()) {
/* Get clipboard html data*/
QString html = mimeData->html();
...
}
else if (mimeData->hasText()) {
/* Get the clipboard plain text data*/
QString text = mimeData->text();
...
}
else {
setText("Cannot display data");
}
(2) Set the content of the system clipboard:
QClipboard *clipboard = QApplication::clipboard();
QMimeData mimeData;
mimeData.setImageData(QPixmap("hello.png")); //image data
// mimeData.setHtml("<h1>Heool world.</h1>"); //Html data
// mimeData.setText("Hello world."); //plain text data
clipboard->setMimeData(&mimeData);