我被困在一个箱子里。我有场景(使用QGraphicsScene),我用方块填充那个场景(使用QGraphicsRectItem)。我想让每一个正方形颜色变成黑色,因为我移动鼠标在广场上按下鼠标按钮。你能告诉我怎么做到这一点吗?我试图用mousePressEvent、mouseMoveEvent、dragEnterEvent等来解决这个问题,我认为这是一个正确的方法,但我不知道如何推动它。为了更好地了解我的情况,我添加了我的代码示例。谢谢你帮忙。
main.cpp
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include "square.h"
#include "background.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// create a scene
QGraphicsScene * scene = new QGraphicsScene(0,0,200,250);
Background * background = new Background();
background->fillBackgroundWithSquares(scene);
// add a view
QGraphicsView * view = new QGraphicsView(scene);
view->show();
return a.exec();
}背景.h
#ifndef BACKGROUND_H
#define BACKGROUND_H
#include <QGraphicsScene>
#include <square.h>
class Background
{
public:
Background();
void fillBackgroundWithSquares(QGraphicsScene *scene);
};
#endif // BACKGROUND_Hbackground.cpp
#include "background.h"
Background::Background()
{
}
void Background::fillBackgroundWithSquares(QGraphicsScene *scene)
{
// create an item to put into the scene
Square *squares[20][25];
// add squares to the scene
for (int i = 0; i < 20; i++)
for (int j = 0; j < 25; j++) {
squares[i][j] = new Square(i*10,j*10);
scene->addItem(squares[i][j]);
}
}square.h .h(编辑)
#ifndef SQUARE_H
#define SQUARE_H
#include <QGraphicsRectItem>
#include <QGraphicsView>
class Square : public QGraphicsRectItem
{
public:
Square(int x, int y);
private:
QPen pen;
protected:
void hoverEnterEvent(QGraphicsSceneHoverEvent * event);
};
#endif // SQUARE_Hsquare.cpp (编辑)
#include "square.h"
Square::Square(int x, int y)
{
// draw a square
setRect(x,y,10,10);
pen.setBrush(Qt::NoBrush);
setPen(pen);
setBrush(Qt::cyan);
setAcceptHoverEvents(true);
setAcceptedMouseButtons(Qt::LeftButton);
show();
}
void Square::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
if ( brush().color() != Qt::black && QApplication::mouseButtons() == Qt::LeftButton)
{
setBrush( Qt::black );
update();
}
}发布于 2018-01-07 17:08:02
试着打电话:
square[j][j]->setAcceptedMouseButtons(...)和
square[i][j]->show() 在创造它之后。
如果要更改悬停事件的颜色,还可以重新实现hoverEnterEvent()和hoverLeaveEvent()。
如果鼠标按钮需要在悬停时按下:在鼠标向下/向上事件中将按钮状态存储在ex变量中。bool isMouseButtonDown并在悬停事件处理程序中检查这一点。您还可以使用: QApplication::mouseButtons()检查按钮状态。
https://stackoverflow.com/questions/48137408
复制相似问题