【Qt筆記】剪貼板

剪貼板的操做常常和前面所說的拖放技術在一塊兒使用。你們對剪貼板都很熟悉。咱們能夠簡單地把它理解成一個數據存儲池,外面的數據能夠存進去,裏面數據也能夠取出來。剪貼板是由操做系統維護的,因此這提供了跨應用程序的數據交互的一種方式。Qt 已經爲咱們封裝好不少關於剪貼板的操做,咱們能夠在本身的應用中很容易實現對剪貼板的支持,代碼實現起來也是很簡單的:函數

class ClipboardDemo : public QWidget
{
    Q_OBJECT
public:
    ClipboardDemo(QWidget *parent = 0);
private slots:
    void setClipboardContent();
    void getClipboardContent();
};

咱們定義了一個ClipboardDemo類。這個類只有兩個槽函數,一個是從剪貼板獲取內容,一個是給剪貼板設置內容。this

ClipboardDemo::ClipboardDemo(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QHBoxLayout *northLayout = new QHBoxLayout;
    QHBoxLayout *southLayout = new QHBoxLayout;

    QTextEdit *editor = new QTextEdit;
    QLabel *label = new QLabel;
    label->setText("Text Input: ");
    label->setBuddy(editor);
    QPushButton *copyButton = new QPushButton;
    copyButton->setText("Set Clipboard");
    QPushButton *pasteButton = new QPushButton;
    pasteButton->setText("Get Clipboard");

    northLayout->addWidget(label);
    northLayout->addWidget(editor);
    southLayout->addWidget(copyButton);
    southLayout->addWidget(pasteButton);
    mainLayout->addLayout(northLayout);
    mainLayout->addLayout(southLayout);

    connect(copyButton, SIGNAL(clicked()), this, SLOT(setClipboardContent()));
    connect(pasteButton, SIGNAL(clicked()), this, SLOT(getClipboardContent()));
}

主界面也很簡單:程序分爲上下兩行,上一行顯示一個文本框,下一行是兩個按鈕,分別爲設置剪貼板和讀取剪貼板。最主要的代碼仍是在兩個槽函數中:操作系統

void ClipboardDemo::setClipboardContent()
{
    QClipboard *board = QApplication::clipboard();
    board->setText("Text from Qt Application");
}

void ClipboardDemo::getClipboardContent()
{
    QClipboard *board = QApplication::clipboard();
    QString str = board->text();
    QMessageBox::information(NULL, "From clipboard", str);
}

槽函數也很簡單。咱們使用QApplication::clipboard()函數得到系統剪貼板對象。這個函數的返回值是QClipboard指針。咱們能夠從這個類的 API 中看到,經過setText()setImage()或者setPixmap()函數能夠將數據放置到剪貼板內,也就是一般所說的剪貼或者複製的操做;使用text()image()或者pixmap()函數則能夠從剪貼板得到數據,也就是粘貼。指針

另外值得說的是,經過上面的例子能夠看出,QTextEdit默認就支持 Ctrl+C, Ctrl+V 等快捷鍵操做的。不只如此,不少 Qt 的組件都提供了很方便的操做,所以咱們須要從文檔中獲取具體的信息,從而避免本身從新去發明輪子。code

QClipboard提供的數據類型不多,若是須要,咱們能夠繼承QMimeData類,經過調用setMimeData()函數讓剪貼板可以支持咱們本身的數據類型。具體實現咱們已經在前面的章節中有過介紹,這裏再也不贅述。orm

在 X11 系統中,鼠標中鍵(通常是滾輪)能夠支持剪貼操做。爲了實現這一功能,咱們須要向QClipboard::text()函數傳遞QClipboard::Selection參數。例如,咱們在鼠標按鍵釋放的事件中進行以下處理:對象

void MyTextEditor::mouseReleaseEvent(QMouseEvent *event)
{
    QClipboard *clipboard = QApplication::clipboard();
    if (event->button() == Qt::MidButton
            && clipboard->supportsSelection()) {
        QString text = clipboard->text(QClipboard::Selection);
        pasteText(text);
    }
}

這裏的supportsSelection()函數在 X11 平臺返回 true,其他平臺都是返回 false。這樣,咱們即可覺得 X11 平臺提供額外的操做。繼承

另外,QClipboard提供了dataChanged()信號,以便監聽剪貼板數據變化。事件

相關文章
相關標籤/搜索