Qt剪贴板
在Qt中使用剪贴板技术是非常简单的,直接使用QClipboard类就可以存取窗口系统的剪贴板。在Qt中是使用QMimeData类来表示剪贴板交换的数据,将一些常用的数据存入到剪贴板可以使用setText(),setImage()和setPixmap()函数。相对应的取数据可以使用text(),image()和pixmap()函数。
下面,通过一个简单的例子来说明这一点。从QWidget继承一个子类ClipboardWidget,该类的头文件clipboardwidget.h如下:
#ifndef CLIPBOARDWIDGET_H #define CLIPBOARDWIDGET_H #include <QtGui> class ClipboardWidget : public QWidget { Q_OBJECT public: ClipboardWidget(QWidget *parent = 0); ~ClipboardWidget(); private slots: void setClipboard(); //设置剪贴板的内容 void getClipboard(); //获取剪贴板的内容 private: QLineEdit *sourceEdit; QLineEdit *targetEdit; }; #endif
clipboardwidget.cpp文件如下:
#include "clipboardwidget.h" ClipboardWidget::ClipboardWidget(QWidget *parent) : QWidget(parent) { sourceEdit = new QLineEdit; targetEdit = new QLineEdit; QLabel *sourceLabel = new QLabel("source :"); QLabel *targetLabel = new QLabel("target :"); sourceLabel->setBuddy(sourceEdit); targetLabel->setBuddy(targetEdit); QPushButton *sourceButton = new QPushButton; sourceButton->setText("copy"); QPushButton *targetButton = new QPushButton; targetButton->setText("paste"); QHBoxLayout *layout1 = new QHBoxLayout; layout1->addWidget(sourceLabel); layout1->addWidget(sourceEdit); QHBoxLayout *layout2 = new QHBoxLayout; layout2->addWidget(targetLabel); layout2->addWidget(targetEdit); QHBoxLayout *layout3 = new QHBoxLayout; layout3->addWidget(sourceButton); layout3->addWidget(targetButton); QVBoxLayout *mainlayout = new QVBoxLayout; mainlayout->addLayout(layout1); mainlayout->addLayout(layout2); mainlayout->addLayout(layout3); mainlayout->addStretch(); setLayout(mainlayout); connect(sourceButton, SIGNAL(clicked()), this, SLOT(setClipboard())); connect(targetButton, SIGNAL(clicked()), this, SLOT(getClipboard())); } ClipboardWidget::~ClipboardWidget() { } void ClipboardWidget::setClipboard() { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(sourceEdit->text()); } void ClipboardWidget::getClipboard() { QClipboard *clipboard = QApplication::clipboard(); targetEdit->setText(clipboard->text()); }
main.cpp文件如下:
#include <QtGui/QApplication> #include "clipboardwidget.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); ClipboardWidget w; w.show(); return a.exec(); }
界面运行结果如下,在source输入字符串"this is clipboard test",然后点击copy按钮,再点击paste按钮,在target就会粘贴这一字符串。总的来说,Qt实现剪贴板是很简单的。