「Qtの基礎 - クリップボード」の版間の差分

ナビゲーションに移動 検索に移動
218行目: 218行目:
   
   
     ImageClipboardExample window;
     ImageClipboardExample window;
    window.show();
    return app.exec();
}
</syntaxhighlight>
<br><br>
== クリップボード監視 ==
以下の例では、クリップボードの変更を監視して、クリップボードの内容が変更されるごとにリアルタイムで通知を受け取り、その内容を表示している。<br>
<br>
これは、クリップボードの監視や、クリップボードを介したアプリケーション間の通信を実装する場合に役立つ。<br>
<br>
テキストクリップボード、画像クリップボード、クリップボード監視をを組み合わせることにより、複雑なクリップボード関連の機能を実装することができる。<br>
例えば、複数の形式のデータを同時に扱ったり、カスタムデータ型をクリップボードで使用したりすることが可能である。<br>
<br>
<syntaxhighlight lang="c++">
// ClipboardMonitorExample.hファイル
#include <QApplication>
#include <QClipboard>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QLabel>
#include <QTextEdit>
class ClipboardMonitorExample : public QMainWindow
{
    Q_OBJECT
private:
    QLabel *statusLabel;
    QTextEdit *contentLabel;
public:
    ClipboardMonitorExample(QWidget *parent = nullptr) : QMainWindow(parent)
    {
      setWindowTitle("Clipboard Monitor Example");
      QVBoxLayout *layout = new QVBoxLayout;
      statusLabel = new QLabel("Clipboard Status: Monitoring", this);
      contentLabel = new QTextEdit(this);
      contentLabel->setReadOnly(true);
      layout->addWidget(statusLabel);
      layout->addWidget(contentLabel);
      QWidget *centralWidget = new QWidget(this);
      centralWidget->setLayout(layout);
      setCentralWidget(centralWidget);
      // クリップボードの監視設定
      QClipboard *clipboard = QApplication::clipboard();
      connect(clipboard, &QClipboard::dataChanged, this, &ClipboardMonitorExample::onClipboardChanged);
    }
private slots:
    // クリップボードからテキストと画像の両方を取得
    // テキストがある場合はそれを表示、画像がある場合はその寸法を表示
    // 取得した情報をQTextEditコントロールに表示して、ステータスラベルを更新
    void onClipboardChanged()
    {
      QClipboard *clipboard = QApplication::clipboard();
      QString text = clipboard->text();
      QPixmap pixmap = clipboard->pixmap();
     
      QString content;
      if (!text.isEmpty()) {
          content = "Text: " + text;
      }
      else if (!pixmap.isNull()) {
          content = "Image: " + QString::number(pixmap.width()) + "x" + QString::number(pixmap.height());
      }
      else {
          content = "Unknown content";
      }
      statusLabel->setText("Clipboard Status: Content changed");
      contentLabel->setText(content);
    }
};
</syntaxhighlight>
<br>
<syntaxhighlight lang="c++">
// main.cppファイル
#include "ClipboardMonitorExample.h"
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    ClipboardMonitorExample window;
     window.show();
     window.show();
   
   

案内メニュー