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();
相关推荐
CDwenhuohuo40 分钟前
uniapp去掉手机状态栏 全屏展示
开发语言·javascript·uni-app
别多香了1 小时前
Python 基础--循环判断&字符串
开发语言·python
早点睡觉好了1 小时前
JAVA中基本类型和包装类型的区别
java·开发语言
慕容雪_1 小时前
springboot jar注册windows服务(WinSW版)
windows·spring boot·jar·服务
码农水水1 小时前
国家电网Java面试被问:二叉树的前序、中序、后序遍历
java·开发语言·面试
Respect@1 小时前
qml之TableViewColumn
开发语言·qml
不吃橘子的橘猫2 小时前
NVIDIA DLI 《Build a Deep Research Agent》学习笔记
开发语言·数据库·笔记·python·学习·算法·ai
算法与双吉汉堡2 小时前
【短链接项目笔记】6 短链接跳转
java·开发语言·笔记·后端·springboot
学Linux的语莫2 小时前
python的基础使用
开发语言·python
charlie072 小时前
qmake工程不能显示手动配置的Kit
qt