How to fix my QClipboard object's behavior?

408 views Asked by At

I'm working with QClipboard object under Windows 10.
Just trying to see what's inside the clipboard when I press Ctrl-C on some sample text.
As you can see the results are very inconsistent and I cannot grasp why exactly.

Code:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(showClipboard()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showClipboard()
{
    qDebug() << "Clipboard is empty:" << QApplication::clipboard()->text().isEmpty()
             << ":" << QApplication::clipboard()->text();
}

Sample output:

Clipboard is empty: false : ""
Clipboard is empty: true : ""
Clipboard is empty: false : "sample text"
Clipboard is empty: false : "sample text"
Clipboard is empty: true : ""
Clipboard is empty: false : ""
Clipboard is empty: false : ""
Clipboard is empty: false : ""
Clipboard is empty: false : "sample text"
Clipboard is empty: true : ""
Clipboard is empty: false : "sample text"
Clipboard is empty: true : ""
1

There are 1 answers

3
pheamit On BEST ANSWER

It seems that introduction of a pause before calling QApplication::clipboard()->text() fixes this issue.
QTimer or plain Sleep()/nanoSleep() (Windows/Linux) can be used to achieve the effect.

QTimer Example:

connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(showClipboard()));

void MainWindow::showClipboard()
{
    QTimer::singleShot(50, this, qDebug() << QApplication::clipboard()->text());
}

Windows Sleep() Example:

connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(showClipboard()));

void MainWindow::showClipboard()
{
    Sleep(50);
    qDebug() << QApplication::clipboard()->text();
}