qt5-入门-剪贴板-简单例子

参考:

C++ GUI Programming with Qt 4, Second Edition

本地环境:

win10专业版,64位,Qt5.12


效果

在输入框中输入内容,点击左侧按钮,剪贴板内容被输入内容替换;点击右侧按钮,会提示剪贴板中内容为何。

实现

核心就一句:QClipboard *board = QApplication::clipboard();

cpp 复制代码
#ifndef CLIPBOARDDEMO_H
#define CLIPBOARDDEMO_H

#include <QtGui>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QTextEdit>
#include <QLabel>
#include <QApplication>
#include <QMessageBox>

class ClipboardDemo : public QWidget
{
    Q_OBJECT

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

        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(setClipboard()));
        connect(pasteButton, SIGNAL(clicked()), this, SLOT(getClipboard()));
    }

private slots:
    void setClipboard() {
        QClipboard *board = QApplication::clipboard();
        //board->setText("Text from Qt Application");
        board->setText(editor->toPlainText());
    }
    void getClipboard() {
        QClipboard *board = QApplication::clipboard();
        QString str = board->text();
        QMessageBox::information(NULL, "From clipboard", str);
    }
private:
    QTextEdit *editor;
};


#endif // CLIPBOARDDEMO_H

// main
// ClipboardDemo w;
// w.show();
相关推荐
思成Codes5 分钟前
Go 语言中数组与切片的本质区别
开发语言·后端·golang
Gofarlic_oms114 分钟前
Cadence许可证全生命周期数据治理方案
java·大数据·运维·开发语言·人工智能·安全·自动化
成为大佬先秃头15 分钟前
渐进式JavaScript框架:Vue — API
开发语言·javascript·vue.js
期待のcode18 分钟前
Java String类
java·开发语言
资生算法程序员_畅想家_剑魔18 分钟前
Java常见技术分享-17-多线程安全-并发编程的核心问题的解决方案
java·开发语言
superman超哥18 分钟前
Rust Trait约束(Trait Bounds):类型能力的精确契约
开发语言·后端·rust·rust trait约束·trait bounds·类型能力·精确契约
myq9920 分钟前
第三章:Java异常处理
java·开发语言·笔记
superman超哥21 分钟前
Rust Where子句的语法:复杂约束的优雅表达
开发语言·后端·rust·rust where子句·复杂约束·优雅表达
靠沿25 分钟前
Java数据结构初阶——堆与PriorityQueue
java·开发语言·数据结构
先做个垃圾出来………26 分钟前
搜索树完整
开发语言·javascript·ecmascript