Button for Creative Coding Asteroids project - button

I'm an undergrad and in one of my classes, we have this assignment to make the Asteroids game (you know, the retro one!) on Processing (which is basically a simplified Javascript program). I have the code for a button:
void setup()
{
size(1280, 720);
}
void draw()
{
background(0,0,0);
drawButton();
}
Boolean pointIsInRectangle(int left, int top, int right, int bottom, int pointX, int pointY)
{
if (pointX >= left
&& pointX <= right
&& pointY <= bottom
&& pointY >= top
)
return true;
else
return false;
}
void drawButton()
{
int left = 350;
int top = 145;
int right = 860;
int bottom = 220;
rectMode(CORNERS);
color background = color(0,0,0);
if (pointIsInRectangle(left,top,right,bottom,mouseX,mouseY))
{
background = color(255);
}
// draw outer rectangle
stroke(255);
fill(background);
rect(left,top,right,bottom);
// draw caption
fill(255);
textSize(100);
text(" ASTEROIDS", left,bottom);
}
and I have the preliminary code for the ship for the game, but I need the button to get to an "in between" page so that when the button is clicked, it leads to a new screen that says "click anywhere to play game" and when any point in the screen is clicked, the ship appears and asteroids begin appearing and the game begins. HOW DO I GET THE BUTTON TO LEAD TO A NEW PAGE, AND HOW DO I CREATE THAT PAGE? I really cannot figure it out. Crossing my fingers that someone will be able to give me some guidance!!!!!
The actual result I'm seeing is that nothing is happening when the button is clicked. This makes sense because I don't know how to add the next page that says Click to Play Game, so this is the issue I'm facing. The code I have so far can be found above.

This is not question about a button, but about a game engine with multiple scenes.
Your game is a collection of screens (scenes). Every scene have definition of visuals, definition of logic, and definition of switch for another scene.
Here is the minimal solution of Your problem.
1 - Define visuals of Your screens in .display() method,
2 - Define logic condition for next screen switch in stateCondition().
boolean mouseReleased;
GameScreen screen;
GameScreen splashScreen;
GameScreen inBetweenPage;
void setup() {
size(1280, 720);
GameScreen splashScreen = new SplashScreen();
GameScreen inBetweenPage = new InBetweenPage();
splashScreen.setNextScreen(inBetweenPage);
inBetweenPage.setNextScreen(splashScreen);
screen = splashScreen;
mouseReleased = false;
}
void draw() {
screen.display();
if (screen.stateCondition()) {
screen = screen.getNextScreen();
}
}
interface GameScreen {
/**
** screen visual definition
**/
void display();
/**
** screen change state condition
**/
boolean stateCondition();
void setNextScreen(GameScreen scr);
GameScreen getNextScreen();
}
class SplashScreen implements GameScreen {
GameScreen nextScreen;
int left = 350;
int top = 145;
int right = 860;
int bottom = 220;
void display() {
background(0, 0, 0);
rectMode(CORNERS);
color background = color(0, 0, 0);
if (pointIsInRectangle(left, top, right, bottom, mouseX, mouseY)) {
background = color(255, 255, 255, 160);
}
// draw outer rectangle
stroke(255);
fill(background);
rect(left, top, right, bottom);
// draw caption
fill(255);
textSize(100);
textAlign(CENTER, CENTER);
text("ASTEROIDS", (left+right)/2, (top+bottom)/2-16);
}
boolean stateCondition() {
if (mouseReleased && (mouseButton == LEFT)) {
mouseReleased = false;
return pointIsInRectangle(left, top, right, bottom, mouseX, mouseY);
}
return false;
}
GameScreen getNextScreen() {
return nextScreen;
}
void setNextScreen(GameScreen target) {
this.nextScreen = target;
}
}
class InBetweenPage implements GameScreen {
GameScreen nextScreen;
int left = 0;
int top = 0;
int right = width;
int bottom = height;
void display() {
background(0, 0, 0);
// draw caption
fill(255);
textSize(24);
textAlign(CENTER, CENTER);
text("< click anywhere to play game >", width/2, height/2);
}
boolean stateCondition() {
if (mouseReleased && (mouseButton == LEFT)) {
mouseReleased = false;
return pointIsInRectangle(left, top, right, bottom, mouseX, mouseY);
}
return false;
}
GameScreen getNextScreen() {
return nextScreen;
}
void setNextScreen(GameScreen target) {
this.nextScreen = target;
}
}
Boolean pointIsInRectangle(int left, int top, int right, int bottom, int pointX, int pointY) {
if (pointX >= left && pointX <= right && pointY <= bottom && pointY >= top) {
return true;
} else
return false;
}
void mouseReleased() {
mouseReleased = true;
}

There is a relatively simple solution to this problem, which would be to make some space for a special "splashscreen" state in your code. It would almost be ninja coding to implement it, although in this case as you are learning it's not taking shortcuts but more like climbing a new step in the learning stairwell. Here's a proof of concept which shows what I'm speaking about:
// this boolean keeps track of the current game state: splashscreen or not
boolean splashScreen = true;
void setup() {
size(600, 400);
}
void draw() {
background(0);
// if the game has yet to start, show the splashscreen
if (splashScreen) {
drawSplashScreen();
} else {
playGame();
}
}
// this method draws the splashScreen
// it could be coded in the 'draw()' method, but it's easier to read this way
void drawSplashScreen() {
textAlign(CENTER);
textSize(30);
fill(255);
text("THIS IS THE SPLASHSCREEN \n click anywhere to play the game", width/2, height/2);
}
// this method contains everything your game loop needs to work
void playGame() {
textAlign(CENTER);
textSize(40);
fill(200, 0, 200);
text("YOU ARE CURRENTLY \n PLAYING THE GAME", width/2, height/2);
}
void mouseClicked() {
if (splashScreen) {
splashScreen = !splashScreen;
}
}
Here you have 2 game states: the splash screen and the game itself, but you could implement more than just these two. There's a design pattern called Finite State Machine that would be just perfect for your needs. Although you already have everything you need to code your assignment, let me explain a little further:
A FSM let you determine the context which can lead to another context and limit some actions to it's own context. A good example of this is Mario in the original Super Mario Bros game: when he's small, getting a magic mushroom will transform him into Super Mario. When he's Super, getting a flower will transform him into Fire Mario. But while small, getting a flower will only make him into Super Mario, not Fire Mario (in the ooold first game at least). That's because each one of these states have rules, and he cannot just jump from one to the other without regard for these.
Your game's logic has it's own rules too: you have the first screen with the "start" button. When this button is clicked, there's a second state where it says "click anywhere to play the game". If the user clicks, then the game itself starts. That makes for 3 states (3 screens if you like) where every state has it's own set of rules - which we often call 'business rules'.
We could schematize this assignment like this:
And here's the skeleton code that would implement such a game, including a bonus rectangle collision detection method:
// the game states are as follow:
// 0 is welcome screen with button
// 1 is click anywhere screen
// 2 is the game itself
int gameState = 0;
void setup() {
size(600, 400);
}
void draw() {
background(0);
// let's use the right game state here
switch(gameState) {
case 0:
drawWelcomeScreen();
break;
case 1:
drawClickAnywhereScreen();
break;
case 2:
playGame();
break;
}
}
void drawWelcomeScreen() {
fill(0, 0, 100);
rect(100, 100, 400, 100);
textAlign(CENTER);
textSize(30);
fill(255);
text("Click here to play", 300, 150);
text("THIS IS THE WELCOME SCREEN", width/2, 50);
}
void drawClickAnywhereScreen() {
textAlign(CENTER);
textSize(30);
fill(255);
text("Click anywhere to play the game", width/2, height/2);
}
void playGame() {
textAlign(CENTER);
textSize(40);
fill(200, 0, 200);
text("YOU ARE CURRENTLY \n PLAYING THE GAME \n click anywhere to go \n back to the welcome screen", width/2, height/2);
}
void mouseClicked() {
// now this will be more complicated, because you'll want to deal with clicks differently depending on the game state
// which kinda answers the question as how we'll deal with this issue: same as in the 'draw()' method
switch(gameState) {
case 0:
// if the click's coordinates are in the rectangle's coordinates (use math here, or a collision method)
// (in fact, use math pretty much everywhere)
// (I hope you like math)
// anyway here's an old collision method I paste everywhere on SO, feel free to steal it and improve on it!
// I wrote it as a student to deal with pretty much the same stuff that you're going through
if (intersect(100, 100, 400, 100, mouseX, mouseY, 1, 1)) {
gameState = 1;
}
break;
case 1:
gameState = 2;
break;
case 2:
gameState = 0;
break;
}
}
// enter the xy coordinates, the width and the heigh of 2 rectangle shapes and it'll return true if they intersect
boolean intersect(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2) {
boolean checkX = false;
boolean checkY = false;
if ( (x1<x2 && (x1+w1)>x2) || (x1<(x2+w2) && (x1+w1)>x2+w2) || (x1>x2 && (x1+w1)<(x2+w2)) ) {
checkX = true;
}
if ( (y1<y2 && (y1+h1)>y2) || (y1<(y2+h2) && (y1+h1)>y2+h2) || (y1>y2 && (y1+h1)<(y2+h2)) ) {
checkY = true;
}
return checkX && checkY;
}
I hope I'm not confusing you with all this material. I'll try and keep an eye out for any question you may have about these things.
Good luck and have fun!

Related

How to erase a QGraphicsItem from QGraphicsView using QPushButton

I am building a major user interface but I am stuck on a problem and in order to shrink the problem I build a small working example that carries exactly the problem.
After the user creates a new .db file using the icon and saving for example to Desktop it is possible to load images(only in .png format for now) in the QGraphicsView and cliking on the checkbox to enable from Right: Drag to Right:Select it is possible to draw boxes on the image. With a right click inside the drawn box we can open a QDialog that asks to name the extracted image from the box. The image is stored in the QTableView as shown in the small working example below:
The problem:
I tried several ways to erase the box (and the related index on the QTableView of the related box) but none of them was successful.
With the use of the "Erase Square" QPushButton I am trying to erase the box. Every box can be re-activated by just left double-clicking within the interested box. See below what I am trying to achieve:
I draw the box on the QGraphicsView and right mouse click to capture the image from the box:
void MainWindow::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(event->button() == Qt::RightButton)
{
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(ShowContextMenu(const QPoint &)));
}
}
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
Q_UNUSED(event);
leftScene->clearSelection(); // Selections would also render to the file
leftScene->setSceneRect(leftScene->itemsBoundingRect()); // Re-shrink the scene to it's bounding contents
QImage image(leftScene->sceneRect().size().toSize(), QImage::Format_ARGB32); // Create the image with the exact size of the shrunk scene
image.fill(Qt::transparent); // Start all pixels transparent
QPainter painter(&image);
leftScene->render(&painter);
QImage subimage = image.copy(QRect(start.toPoint(), end.toPoint()));
clipSceneDialog d(this);
d.show();
d.setImage(subimage);
d.setHeaderImage(currentLeftImagePath);
d.setBoundingBox(QRect(start.toPoint(), end.toPoint()));
if(d.exec() == QDialog::Rejected) {
return;
} else {
//
}
Param result = d.getData();
Parameters* param = new Parameters(result);
mDatabaseLeftCamera->addItem(param);
mModelLeftCamera->select();
ui->tableView->show();
}
Draw as many boxes as the user wants:
void MainWindow::onRubberBandUpdate(const QRect &viewportRect,
const QPointF &fromScenePoint,
const QPointF &toScenePoint)
{
if(viewportRect.isNull() && fromScenePoint.isNull() && toScenePoint.isNull() && imageLoaded)
{
if(currentSelection >= 0)
selections[currentSelection]->setActiveState(false);
QRectF select;
select.setCoords(start.x(), start.y(), end.x(), end.y());
square = new Square(select);
square->setActiveState(true);
currentSelection = selections.size();
selections.append(square);
leftScene->addItem(square->getGraphics());
ui->graphicsView->show();
}
else
{
start = fromScenePoint;
end = toScenePoint;
}
}
After drawing several boxes the user decides to reactivate one of the boxes by double-cliking within the box:
void MainWindow::onSceneDoubleClick(QPointF point)
{
qDebug() << "Click!";
QList<QGraphicsItem*> foundItems = leftScene->items(point);
if(foundItems.size() > 0 && foundItems[0]->group() != nullptr)
{
qDebug() << "Found";
int i = 0;
for(i=0;i<selections.size();i++)
{
qDebug() << "Iterate";
if(selections[i]->getGraphics() == foundItems[0]->group())
{
qDebug() << "Target";
break;
}
}
if(currentSelection >= 0)
selections[currentSelection]->setActiveState(false);
currentSelection = i;
selections[currentSelection]->setActiveState(true);
}
}
The user decides to erase the re-activated square:
void MainWindow::on_eraseSquare_clicked()
{
clearSceneLeft();
}
void MainWindow::clearSceneLeft()
{
if (selections.size() > 0) {
qDeleteAll(selections);
selections.clear();
currentSelection = -1;
}
for(int p=0;p<shape.size();p++)
{
leftScene->removeItem(shape[p]);
delete shape[p];
}
shape.clear();
}
But this is not working and nothing happens. Additionally because the box corresponds to an SQL reference on the QTableView I dont know how that could be connected in the SQL class.
I have been trying for many days to solve this problem and am running out of ideas. Thanks for shedding light on this problem or point in the right direction.
If you would like to try the small example interface you can do it from here

Implement selection on QChartView

I want to make an implementation of chart selection based on QChart and QChartView.
The family of the classes have a big advantage - easy use of openGL and animations, for example:
QLineSeries *series = new QLineSeries();
series->setUseOpenGL(true); // <==
QChart *chart = new QChart();
chart->addSeries(series);
chart->setAnimationOptions(QChart::AllAnimations); // <==
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
The QChartView class provides the useful zoom feature - QChartView::setRubberBand():
chartView->setRubberBand(QChartView::RectangleRubberBand);
The main problem is that the rubber band can be used only for zoom, but I need to implement it for horizontal selection without zoom, as the feature usually implemented in audio editors:
Now, when I have inherit QChartView, I can disable zoom after selection:
class ChartView : public QChartView
...
bool m_drawRubberBand;
QRubberBand m_rubberBand;
...
ChartView::ChartView(QChart *chart, QWidget *parent)
: QChartView(chart, parent)
{
setRubberBand(QChartView::HorizontalRubberBand);
}
...
// Just copy-paste from the Qt 5 sources - file \Src\qtcharts\src\charts\qchartview.cpp:
/*!
If the rubber band rectangle is displayed in the press event specified by
\a event, the event data is used to update the rubber band geometry.
Otherwise, the default QGraphicsView::mouseMoveEvent() implementation is called.
*/
void ChartView::mouseMoveEvent(QMouseEvent *event)
{
if (m_drawRubberBand && m_rubberBand.isVisible())
{
QRect rect = chart()->plotArea().toRect();
int width = event->pos().x() - m_rubberBandOrigin.x();
int height = event->pos().y() - m_rubberBandOrigin.y();
if (!rubberBand().testFlag(VerticalRubberBand))
{
m_rubberBandOrigin.setY(rect.top());
height = rect.height();
}
if (!rubberBand().testFlag(HorizontalRubberBand))
{
m_rubberBandOrigin.setX(rect.left());
width = rect.width();
}
m_rubberBand.setGeometry(QRect(m_rubberBandOrigin.x(), m_rubberBandOrigin.y(), width, height).normalized());
}
else
{
QGraphicsView::mouseMoveEvent(event);
}
}
Then I can just don't implement the zoom action on the mouse key release event:
void ChartView::mouseReleaseEvent(QMouseEvent *event)
{
if (m_rubberBand.isVisible())
{
if (event->button() == Qt::LeftButton)
{
m_drawRubberBand = false;
do_nothing(); // <==
}
}
}
So, my questions now:
How borders of the the visual rubber band can be mapped to real chart's coordinates. I.e., how can the selection be mapped into a line series on the chart? Now I receive same wrong coordinates:
void MyView::resizeEvent(QResizeEvent *event)
{
QChartView::resizeEvent(event);
QRect rct(QPoint(10, 10), QPoint(20, 20));
qDebug() << mapToScene(rct); <==
}
Output:
QPolygonF(QPointF(10,10)QPointF(21,10)QPointF(21,21)QPointF(10,21))
QPolygonF(QPointF(10,10)QPointF(21,10)QPointF(21,21)QPointF(10,21))
QPolygonF(QPointF(10,10)QPointF(21,10)QPointF(21,21)QPointF(10,21))
QPolygonF(QPointF(10,10)QPointF(21,10)QPointF(21,21)QPointF(10,21))
...
How can an existing rubber selection be proportionally resized together with the view?
Edit: May be it is a useful keyword - QGraphicsScene::setSelectionArea().
The Qt 5 chip example which provides nice rubber band selection, but the example based on QGraphicsView, not on QChartView.
The question is resolved thanks to the reply to this answer: Get mouse coordinates in QChartView's axis system
The key moment: it was necessary to invoke QChart::mapToValue() for a correct coordinates transform:
QPointF ChartView::point_to_chart(const QPoint &pnt)
{
QPointF scene_point = mapToScene(pnt);
QPointF chart_point = chart()->mapToValue(scene_point);
return chart_point;
}
And the inverse transformation:
QPoint ChartView::chart_to_view_point(QPointF char_coord)
{
QPointF scene_point = chart()->mapToPosition(char_coord);
QPoint view_point = mapFromScene(scene_point);
return view_point;
}
That's how I have implemented resize of the rubber band on the resizeEvent.
Firstly, I save the current rubber band on mouse release event:
void ChartView::mouseReleaseEvent(QMouseEvent *event)
{
if (m_rubberBand.isVisible())
{
update_rubber_band(event);
m_drawRubberBand = false;
save_current_rubber_band(); <==
}
}
Where:
void ChartView::update_rubber_band(QMouseEvent * event)
{
QRect rect = chart()->plotArea().toRect();
int width = event->pos().x() - m_rubberBandOrigin.x();
int height = event->pos().y() - m_rubberBandOrigin.y();
if (!rubberBand().testFlag(VerticalRubberBand))
{
m_rubberBandOrigin.setY(rect.top());
height = rect.height();
}
if (!rubberBand().testFlag(HorizontalRubberBand))
{
m_rubberBandOrigin.setX(rect.left());
width = rect.width();
}
m_rubberBand.setGeometry(QRect(m_rubberBandOrigin.x(), m_rubberBandOrigin.y(), width, height).normalized());
}
And:
void ChartView::save_current_rubber_band()
{
QRect rect = m_rubberBand.geometry();
QPointF chart_top_left = point_to_chart(rect.topLeft());
m_chartRectF.setTopLeft(chart_top_left);
QPointF chart_bottom_right = point_to_chart(rect.bottomRight());
m_chartRectF.setBottomRight(chart_bottom_right);
}
And how I repaint the rubber on the resize event:
void ChartView::resizeEvent(QResizeEvent *event)
{
QChartView::resizeEvent(event);
if (m_rubberBand.isVisible())
{
restore_rubber_band();
}
apply_nice_numbers();
}
Where:
void ChartView::restore_rubber_band()
{
QPoint view_top_left = chart_to_view_point(m_chartRectF.topLeft());
QPoint view_bottom_right = chart_to_view_point(m_chartRectF.bottomRight());
m_rubberBandOrigin = view_top_left;
m_rubberBand.setGeometry(QRect(view_top_left, view_bottom_right));
}
And don't forget about the "nice numbers":
void ChartView::apply_nice_numbers()
{
QList<QAbstractAxis*> axes_list = chart()->axes();
for each(QAbstractAxis* abstract_axis in axes_list)
{
QValueAxis* value_axis = qobject_cast<QValueAxis*>(abstract_axis);
if (value_axis)
{
value_axis->applyNiceNumbers();
}
}
}
This logic in action.
Before resize:
After resize:

Move QGraphicsView top left to a certain point in QGraphicsScene manually

I have a QGraphicsView subclass, holding a QGraphicsScene subclass, inside a QWidget.
The QGraphicsScene has an actual drawing rectangle with top let corner at (0,0) (so the scene really has a QRectF(-x,-y,w,h) of values irrelevant to the problem).
On startup, actually in the showEvent of the widget, I set the size of the scene to fit the custom sized rectangle. That also centers it.
What I would like, is to match the (0,0) point of the scene to the top left of the view, on start.
Unlike other questions with the same title, I actually need to move the view, not the items inside the scene.
Image 1: actual start, image 2: desired
I am trying:
void MyWidget::showEvent(QShowEvent *event)
{
static bool startUp = true;
if(startUp)
{
QSizeF sz = m_scene->getActualSize();
ui->graphicsView->fitInView(QRectF(0, 0, sz.width(), sz.height()), Qt::KeepAspectRatio);
QPointF zero = ui->graphicsView->mapFromScene(QPointF(0,0));
ui->graphicsView->translate(-zero.x(), -zero.y()); // or positive
startUp = false;
}
QWidget::showEvent(event);
}
note: I use the fitInView to get the desired zoom - and it also brings the desired rectangle in focus - but centered in the view.
I also tried
void GraphicsView::alignToZero()
{
QPointF zero = this->mapFromScene(QPointF(0,0));
this->scrollContentsBy(-zero.x(), -zero.y());
}
void MyWidget::showEvent(QShowEvent *event)
{
static bool startUp = true;
if(startUp)
{
QSizeF sz = m_scene->getActualSize();
ui->graphicsView->fitInView(QRectF(0, 0, sz.width(), sz.height()), Qt::KeepAspectRatio);
ui->graphicsView->alignToZero();
startUp = false;
}
QWidget::showEvent(event);
}
Still no result.
Also tried
void MyWidget::showEvent(QShowEvent *event)
{
static bool startUp = true;
if(startUp)
{
QSizeF sz = m_scene->getActualSize();
ui->graphicsView->fitInView(QRectF(0, 0, sz.width(), sz.height()), Qt::KeepAspectRatio);
QPointF zero = ui->graphicsView->mapFromScene(QPointF(0,0));
//ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
ui->graphicsView->horizontalScrollBar()->setValue(zero.x());
ui->graphicsView->verticalScrollBar()->setValue(zero.y());
startUp = false;
}
QWidget::showEvent(event);
}
This, with or without the alignment setting (which I think may have unwanted effects elsewhere), moves the view... too far.
If I understand your question correctly, to achieve desired effect you can use method
QGraphicsView::setAlignment(Qt::Alignment alignment):
ui->graphicsView->setAlignment( Qt::AlignTop | Qt::AlignLeft );
Which is commented in your code.
This method with those arguments aligns view top-left, you don't have to move or fit anything.
While there must be a better way... I figured out a way to get my 0's aligned by doing fitInView twice:
void MyWidget::showEvent(QShowEvent *event)
{
static bool startUp = true;
if(startUp)
{
QSizeF sz = m_scene->getActualSize();
// First I do a normal `fitInView` that centers the rectangle
ui->graphicsView->fitInView(QRectF(0, 0, sz.width(), sz.height()), Qt::KeepAspectRatio);
// Then, knowing the shift, I fit it again adding twice the shift to the size.
QPointF zero = ui->graphicsView->mapToScene(QPoint(0,0));
ui->graphicsView->fitInView(QRectF(0, 0, sz.width() - 2 * zero.x(), sz.height() - 2 * zero.y()), Qt::KeepAspectRatio);
startUp = false;
}
QWidget::showEvent(event);
}

zooming GraphicsView with wheelEvent

Im implementing the zooming of my QGraphicsView using wheelEvent
void View::wheelEvent(QWheelEvent *e)
{
if (e->modifiers().testFlag(Qt::ControlModifier)){ // zoom only when CTRL key pressed
int numSteps = e->delta() / 15 / 8;
if (numSteps == 0) {
e->ignore();
return;
}
qreal sc = pow(1.25, numSteps); // I use scale factor 1.25
this->zoom(sc);
e->accept();
}
}
and the zoom item
void View::zoom(qreal scaleFactor)
{
scale(scaleFactor, scaleFactor);
}
here i don’t want to zoom out too deeper, all i need it to restrict the scaling to certain point , i have to limit the zoom out so i tried to find the transform point
qreal
View::zoomScale() const
{
return transform().m11();
}
but with this i cant able to restrict the zooming .
please help me find the solution.
You can calculate the zoom factor relative to the "normal zoom" and decide if you can zoom or not.
For example, you can take a QRect for reference and check its size after the zoom :
void ClassA::scale(qreal scaleFactor) {
QRectF(0, 0, 1, 1); // A reference
qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(r).width(); // absolute zoom factor
if ( factor > 20 ) { // Don't zoom more than 20x
return;
}
this->scale(scaleFactor, scaleFactor);
}

Prevent QGraphicsItem from moving outside of QGraphicsScene

I have a scene which has fixed dimensions from (0;0) to (481;270):
scene->setSceneRect(0, 0, 481, 270);
Inside of it, I have a custom GraphicsItem and I can move it thanks to the flag ItemisMovable, but I would like it to stay within the Scene; I actually mean I don't want it to have coordinates neither under (0;0) nor over (481;270).
I tried several solutions like overriding QGraphicsItem::itemChange() or even QGraphicsItem::mouseMoveEvent() but I still cannot manage to reach what I want to do.
What is the suitable solution for my needs? Do I use QGraphicsItem::itemChange() badly?
Thanks in advance.
You can override QGraphicsItem::mouseMoveEvent() like this:
YourItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mouseMoveEvent(event); // move the item...
// ...then check the bounds
if (x() < 0)
setPos(0, y());
else if (x() > 481)
setPos(481, y());
if (y() < 0)
setPos(x(), 0);
else if (y() > 270)
setPos(x(), 270);
}
This code keeps your complete item in scene. Not only the upper left pixel of your item.
void YourItem::mouseMoveEvent( QGraphicsSceneMouseEvent *event )
{
QGraphicsItem::mouseMoveEvent(event);
if (x() < 0)
{
setPos(0, y());
}
else if (x() + boundingRect().right() > scene()->width())
{
setPos(scene()->width() - boundingRect().width(), y());
}
if (y() < 0)
{
setPos(x(), 0);
}
else if ( y()+ boundingRect().bottom() > scene()->height())
{
setPos(x(), scene()->height() - boundingRect().height());
}
}
Warning: The suggested solutions won't work for multiply selected items. The problem is, only one of the items receives a mouse move event in that case.
Actually, the Qt Documentation on QGraphicsItem provides an example which exactly solves the problem of limiting the movement of items to the scene rect:
QVariant Component::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange && scene()) {
// value is the new position.
QPointF newPos = value.toPointF();
QRectF rect = scene()->sceneRect();
if (!rect.contains(newPos)) {
// Keep the item inside the scene rect.
newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
Note I: You'd have to enable the QGraphicsItem::ItemSendsScenePositionChanges flag:
item->setFlags(QGraphicsItem::ItemIsMovable
| QGraphicsItem::ItemIsSelectable
| QGraphicsItem::ItemSendsScenePositionChanges);
Note II: If you only want to react on finished movement, consider using the GraphicsItemChange flag ItemPositionHasChanged

Resources