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();
相关推荐
Sylvia33.12 分钟前
足球数据接口开发实战:如何用火星数据API盘活赛事应用
java·服务器·开发语言·数据库·python
z落落16 分钟前
C# WinForm 自定义控件
开发语言·c#
geovindu1 小时前
go: Enumeration Algorithm
开发语言·后端·算法·golang·枚举算法
气概2 小时前
QT集成basler相机
开发语言·数码相机·qt
苦瓜汤补钙2 小时前
Oracle JDK8 环境配置-Win11
开发语言·数据库·笔记·oracle
overmind2 小时前
oeasy Python 102 集合_运算_交集_并集_差集_对称差集
开发语言·python
研☆香2 小时前
JavaScript 绘制简单不规则图形:三角形与五角星实战教程
开发语言·javascript·ecmascript
酉鬼女又兒3 小时前
零基础入门Vibe Coding实战:从RAG项目开发到测试部署全流程指南
开发语言·人工智能·机器学习·json
数聚天成DeepSData3 小时前
企业知识库 RAG 数据准备与文档清洗:Dify、RAGFlow、扣子选型指南
开发语言·人工智能·机器学习·自然语言处理·sentinel·cocos2d
我是唐青枫3 小时前
Java SLF4J 实战指南:从日志门面到 Logback、MDC 和链路追踪
java·开发语言·logback