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();
相关推荐
ALe要立志成为web糕手24 分钟前
数据库脱裤
数据库·windows·mysql·web安全·网络安全·adb·mssql
胡乱儿起个名25 分钟前
《高阶函数:把函数当玩具传来传去》
开发语言·c++·算法
七七知享26 分钟前
开启 Python 编程之旅:基础入门实战班全解析
开发语言·python·程序人生·程序员·零基础·实战
repetitiononeoneday27 分钟前
java基础课程-springmvc课程
java·开发语言
古月居GYH44 分钟前
嵌入式C语言高级编程:OOP封装、TDD测试与防御性编程实践
c语言·开发语言·tdd
ghost1431 小时前
Python自学第1天:变量,打印,类型转化
开发语言·python·学习
დ旧言~1 小时前
【Qt】界面优化
qt
汤姆_5111 小时前
【c语言】深入理解指针1
c语言·开发语言
gospace1 小时前
Golang Event Bus 最佳实践:使用 NSQite 实现松耦合架构
开发语言·架构·golang·事件·总线·event·event bus
风中飘爻1 小时前
JavaScript:表单及正则表达式验证
开发语言·javascript·ecmascript