10.4.  Clipboard and Data Transfer Operations

[ fromfile: clipboard.xml id: clipboard ]

Sometimes it is necessary to take data from one place and "send" it to another. One way is clipboard "cut and paste", and another is "drag and drop". The data transfer classes used are the same for both.

Every Qt application has access to the system clipboard from qApp->clipboard(). The clipboard holds onto typed data (text, graphics, URLs, or custom data). To place data into the clipboard, you create a QMimeData, encode the data somehow, and call QClipBoard->setMimeData().

Example 10.10. src/clipboard/mainwindow.cpp

[ . . . . ]
MainWindow::MainWindow(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect (qApp->clipboard(), SIGNAL(changed(QClipboard::Mode)),
             this, SLOT(clipboardChanged(QClipboard::Mode)));
}

void MainWindow::clipboardChanged(QClipboard::Mode) {
    QStringList sl;
    QClipboard *cb = qApp->clipboard();
    const QMimeData *md = cb->mimeData();
    sl << "Formats: " + md->formats().join(",");
    foreach (QString format, md->formats()) {
        QByteArray ba = md->data(format);
        sl << "   " + format + ": " + QString(ba);
    }
    ui->clipboardContentsEdit->setText(sl.join("\n"));
}
[ . . . . ]

In Example 10.10 we connect the system clipboard's changed signal to the MainWindow clipboardChanged() slot. That signal is emitted whenever any application copies something into the clipboard. You can run this example and see what data types are available when you copy data from the QTextEdit or from other applications.

Figure 10.8 shows what happens when text is copied from the QTextEdit. In this case, clipboard data is encoded in three ways, plain text, HTML, and an OASIS opendocument format. You can choose which format to use depending on what kind of data you need in the paste or drop object.

Figure 10.8.  System Clipboard Demo

System Clipboard Demo