我使用 Qt。中央小部件:.h 文件:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <gameboard.h>
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
GameBoard* gb;
protected:
void resizeEvent(QResizeEvent *event);
};
#endif // MAINWINDOW_H
构造函数:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
gb=new GameBoard(this);
}
游戏板类:
.h 文件:
class GameBoard : public QGraphicsView
{
friend class MainWindow;
public:
GameBoard(QWidget *parent);
private:
QVBoxLayout* mainLayout;
QGraphicsView* gameBoard;
QGraphicsScene* scene;
protected:
void mouseMoveEvent(QMouseEvent *event);
};
.cpp:
GameBoard::GameBoard(QWidget *parent)
{
gameBoard = new QGraphicsView();
mainLayout = new QVBoxLayout();
gameBoard->setParent(parent);
gameBoard->setMinimumSize(parent->width(),parent->height());
gameBoard->viewport()->setMouseTracking(true);
scene=new QGraphicsScene();
QPen pen;
QColor black(0,0,0);
pen.setColor(black);
scene->addEllipse(0, 0, 10,10, pen, QBrush(Qt::SolidPattern));
gameBoard->setScene(scene);
}
void GameBoard::mouseMoveEvent(QMouseEvent *event)
{
qDebug()<<event->pos().x();
}
用作示例:
https://pro-prof.com/forums/topic/qgraphicsscene-drawing
我决定在这里用英语仔细检查 SO - 同样的方式,标记为解决方案:
https://stackoverflow.com/questions/18817538/how-to-use-mouse-move-event-for-qgraphicsscene
UPD:我忘了澄清即使按下鼠标左键,该事件也不起作用。
默认情况下,不跟踪鼠标移动事件,并且 GameBoard::mouseMoveEvent 只会在按下鼠标按钮移动时触发。如果您正在制作图纸,您可能不需要更多。但是如果需要流鼻血,那么就像这样: