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();
相关推荐
A***071712 分钟前
C++在游戏中的阴影渲染
开发语言·c++·游戏
2401_8370885015 分钟前
Redisson的multilock原理
java·开发语言
合作小小程序员小小店29 分钟前
桌面开发,在线%超市销售管理%系统,基于vs2022,c#,winform,sql server数据
开发语言·数据库·microsoft·c#
Q***l6871 小时前
C++在计算机图形学中的渲染
开发语言·c++
q***82911 小时前
windows同时安装两个不同版本的Mysql
windows·mysql·adb
0和1的舞者1 小时前
《网络编程核心概念与 UDP Socket 组件深度解析》
java·开发语言·网络·计算机网络·udp·socket
惜棠1 小时前
visual code + rust入门指南
开发语言·后端·rust
n***i951 小时前
Rust在嵌入式系统中的内存管理
开发语言·后端·rust
q***06291 小时前
ThinkPHP和PHP的区别
开发语言·php
Java天梯之路2 小时前
Java 初学者必看:接口 vs 抽象类,到底有什么区别?
java·开发语言