0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Qt】マウスカーソルの下にポインタを付けてみた【C++】

Last updated at Posted at 2025-07-29

Qtでマウスカーソルの下にポインタを付けてみました。

内容は以下になります。

main.cpp

#include <QApplication>     // Qtアプリケーション用
#include <QWidget>          // GUIの基本クラス
#include <QPainter>         // 描画(ペイント)に使う
#include <QTimer>           // 一定間隔で処理するためのタイマー
#include <QCursor>          // マウスカーソルの位置取得に使う
#include <QKeyEvent>        // キーボード入力イベント
#include <QMouseEvent>      // マウスクリックイベント

// ポインタ表示用のクラス
class PointerFollower : public QWidget {
public:
    PointerFollower() {
        // ウィンドウの設定(枠なし・常に最前面・タスクバーに出ない)
        setWindowFlags(Qt::FramelessWindowHint |
                       Qt::WindowStaysOnTopHint |
                       Qt::Tool);

        // 背景を透明にする
        setAttribute(Qt::WA_TranslucentBackground);

        // キー入力を受け取るための設定
        setFocusPolicy(Qt::StrongFocus);

        // ウィンドウのサイズ(円の大きさ)
        resize(circleSize, circleSize);

        // タイマーで定期的にカーソル位置を取得して移動
        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &PointerFollower::updatePosition);
        timer->start(16); // 約60回/秒(16ミリ秒ごと)
    }

protected:
    // 円を描画する関数
    void paintEvent(QPaintEvent *) override {
        QPainter painter(this);                 // 描画ツール
        painter.setRenderHint(QPainter::Antialiasing);  // なめらかな描画
        painter.setBrush(Qt::red);              // 赤い塗りつぶし
        painter.setPen(Qt::NoPen);              // 枠線なし
        painter.drawEllipse(rect());            // ウィンドウ全体に円を描く
    }

    // キーボードが押されたときの処理
    void keyPressEvent(QKeyEvent *event) override {
        if (event->key() == Qt::Key_Escape) {   // Escキーが押されたら
            close();                            // ウィンドウを閉じる
        }
    }

    // マウスがクリックされたときの処理
    void mousePressEvent(QMouseEvent *) override {
        close();                                // クリックでも閉じる
    }

private:
    const int circleSize = 20;  // 円の大きさ(20ピクセル)

    // カーソルの位置にウィンドウを移動する関数
    void updatePosition() {
        QPoint pos = QCursor::pos();  // 現在のカーソル位置を取得
        // カーソルの中心に円がくるように移動
        move(pos.x() - circleSize / 2, pos.y() - circleSize / 2);
    }
};

// アプリのメイン関数
int main(int argc, char *argv[]) {
    QApplication app(argc, argv);  // Qtアプリケーションの起動

    PointerFollower pointer;       // ポインタウィジェットを作成
    pointer.show();                // 表示

    return app.exec();             // アプリケーションの実行開始
}

↓↓youtube
https://youtu.be/HWAAIIpqy7k

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?