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();
相关推荐
MATLAB代码顾问16 小时前
Python实现蜂群算法优化TSP问题
开发语言·python·算法
jinanwuhuaguo17 小时前
(第三十三篇)五月的文明奠基:OpenClaw 2026.5.2版本的文明级解读
android·java·开发语言·人工智能·github·拓扑学·openclaw
有一个好名字18 小时前
工具即双手 —— 从 Bash 到 Tool Dispatch Map
开发语言·chrome·bash
Lyyaoo.18 小时前
优惠券秒杀业务分析
java·开发语言
DevilSeagull18 小时前
MySQL(2) 客户端工具和建库
开发语言·数据库·后端·mysql·服务
MATLAB代码顾问19 小时前
改进遗传算法(IGA)求解作业车间调度问题(JSSP)——附MATLAB代码
开发语言·matlab
怪兽软家19 小时前
DaVinci Resolve/达芬奇 20安装教程及下载
windows·经验分享·生活
chao18984419 小时前
完整MES系统实现 (C# 客户端服务器)
服务器·windows·c#
syker19 小时前
AIFerric深度学习框架:自研全栈AI基础设施的技术全景
开发语言·c++
HSunR19 小时前
dify 搭建ai作业批改流
开发语言·前端·javascript