QGraphicsItem drawing problem - c++

I am working on a small Tower Defense game in order to learn Qt. I am using a QGraphicsScene to hold all the object of the game. To make them move, I am not using the Animation framework but I'm calling the advance() method along with a QTimer.
I'd like to make my projectiles explode when they hit an enemy. The problem is that when I'm trying to draw an ellipse to simulate the explosion, it doesn't get drawn correctly.
You can see the problem in this video.
I tried to play with the z-indexes but it didn't change anything.
Here's the code I use to draw the projectile :
void Projectile::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
if(!isExploding) {
painter->drawPixmap(boundingRect().toRect(), image);
} else {
if(cnt < 50) {
painter->setBrush(QBrush(explosion));
painter->drawEllipse(-cnt, -cnt, 2.0*cnt, 2.0*cnt);
cnt++;
} else {
this->isFinished = 1;
}
}
}
QRectF Projectile::boundingRect() const
{
// Taille de l'image de l'insecte
return QRectF(0, 0, 6, 6);
}
Do you have any clues on how to solve this problem?
Thank you.

Say cnt is 3.
You are drawing an ellipse with
painter->drawEllipse(-3,-3,6,6)
This would require a boundingRect with at least a width and height of 9.
Also the boundingRect is specified using the internal item coordinate system. You are drawing from (-3,-3) to (6,6) which is outside of the boundingRect.

Related

How i can increase a distance btween the rectangle shape in a scene?

Good Morning every one.
I create a code in QT creator using c++ language,my problem is when I draw a rectangular shapes in scene, this shapes were very close something like this.This are the x{45,45,42,40,35,35,40} and the y {68,70,68,66,66,69,69} coordinates.
When I zoom the distance between the rectangles should not be changed.
this is the part of my code that I have created for drawing the shapes:
//steps for draw the store
QGraphicsScene * scene=new QGraphicsScene();
QString st=sl[0];//sl it is a liste contains the coordiantes.
listDX=st.split(',');
st=sl[1];
listDY=st.split(',');
for(int i=0;i<listDX.length();i++)
{
if(listDX[i]!=" " && listDY[i]!=" ")
{
QGraphicsRectItem *rect=new QGraphicsRectItem();
rect->setRect(listDX[i].toInt(),listDY[i].toInt(),20,20);
QRadialGradient gradient(-3, -3, 10);
gradient.setCenter(3, 3);
gradient.setFocalPoint(3, 3);
gradient.setColorAt(1, QColor(Qt::red).light(120));
gradient.setColorAt(0, QColor(Qt::darkRed).light(120));
rect->setBrush(gradient);
rect->setPen(QPen(Qt::black, 0));
//add the item to the scene
scene->addItem(rect);
}
Thanks for the help

QT QGraphicsView rotation

Disclaimer: I am pretty much a beginner with QT.
I've been struggling for some time to rotate a QGraphicsView (no 3D rotation) but, despite what i do, it doesn't work. I have tried:
QTransform transform;
transform.rotate(45);
ui->graphicsView->setTransform(transform);
or more simply:
ui->graphicsView->rotate(45);
These seem like very straightforward ways to do it that should work, but for some reason, whenever i run it, the QGraphicsView doesn't rotate at all. If possible, i'd like some direct and easy to understand code snippets, and/or what i'm doing wrong.
EDIT: This is the code in the widget cpp file i have problems with. It should be a simple timer with an animated hourglass icon. It gets repeated every .5 seconds.
void Widget::timerEvent(QTimerEvent *event)
{
++timeFlag;
++timerFlag;
if (timerFlag < 115){
animateTimer = QString("\":/new/100/timerFrames/timerIconFrame%1.png\"").arg(timerFlag);
QPixmap pix(animateTimer);
pixmapitem.setPixmap(pix);
scene.addItem(&pixmapitem);
ui->graphicsView_2->setScene(&scene);
}
if (timerFlag >= 115 && timerFlag < 119){
//
}
if(timerFlag == 119){
ui->graphicsView_2->setStyleSheet("border-image:url(:/new/100/timerIconPix.PNG);border:0px;}");
}
if(timerFlag == 120){
timerFlag = 0;
}
if (timeFlag==2){
timeFlag = 0;
if(sec>=10){
ui->label_2->setText(QString("%1:%2").arg(min).arg(sec));
} else {
ui->label_2->setText(QString("%1:0%2").arg(min).arg(sec));
}
++sec;
if (sec == 60) {
sec = 0;
++min;
}
}
}
You're merely decorating the QGraphicsView using the style mechanism. You could have used a plain QWidget instead, since you don't use any graphics view functionality. None of the images in the stylesheet are what the view actually displays. The image must be on the scene displayed by the view.
Set the image on a QGraphicsPixmapItem, add that item to a scene, set the scene on the view, and then the transformations will work. You can then keep replacing the pixmap in the timer handler.
Finally, you must also check the timer id in the timerEvent. I assume that you're using a QBasicTimer, say called m_timer, you'd then check as follows:
void Widget::timerEvent(QTimerEvent * ev) {
if (ev->timerId() != m_timer.timerId()) return;
... // rest of the code
}
As you can see, the code that you've not included in the original question was absolutely essential! Without it, the question was wholly off-topic.
You need to implement a QGraphicsView, a QGraphicsScene and then add something that inherits from QGraphicsItem to that scene to rotate.
Here is an example that rotates a QWidget in a QGraphicsView:
QGraphicsView* view = new QGraphicsView(parent);
QGraphicsScene* scene = new QGraphicsScene(view);
view->setScene(scene);
// Widget to rotate - important to not parent it
QWidget* widget = new QWidget();
QProxyWidget proxy_widget = scene_->addWidget(widget);
QPropertyAnimation* animation = new QPropertyAnimation(proxy_widget, "rotation");
animation->setDuration(5000);
animation->setStartValue(0);
animation->setEndValue(360);
animation->setEasingCurve(QEasingCurve::Linear);
animation->start(QAbstractAnimation::DeleteWhenStopped);

Proper data model for a 2D Tilemap (C++, Qt)

I made a small 2D level editor where you can create 2D tile based maps..however, the performance inside my application is really really bad. I am currently thinking to start all over again.
The Problem is, I currently use QGraphicsItem's to represent a single tile inside a QGraphicsScene. A tile has some properties..including an image. When a map is created, I create an item for each tile which draws an image for each tile..which basically is a lot of graphicitems and it slows down the whole application. This is the function that populates a map once it is created :
for(int i=0;i<map->m_rows;i++)
{
for(int j=0;j<map->m_cols;j++)
{
Tile* thetile=map->getAt(i,j);
if(thetile)
{
if(map->getType()==twoditor::RECTANGLETILE)
{
QGraphicsItem* item= new TileGraphicsItem(thetile);
m_scene->addItem(item);
}
else if(map->getType()==twoditor::HEXAGONTILE)
{
QGraphicsItem* item= new HexagonGraphicsItem(thetile);
m_scene->addItem(item);
}
}
}
}
This works for a map with 100x100 Tiles. But if i want to create even larger maps..the loading time is really unbearable..
Can someone give me advice for a better representation of a tile map? Are there other convenient ways to show a map and edit cells(tiles) inside it?
EDIT: TileGraphicItem paint function:
void TileGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget){
setZValue(0);
if(!m_thetile->getImage().isNull())
{
painter->drawImage(0,0,m_thetile->getImage());
}
QPainterPath circle_path;
QRect duwagrect(boundingRect().x(),boundingRect().y(),boundingRect().width(),boundingRect().height());
circle_path.addRect(duwagrect);
m_pen.setStyle(Qt::SolidLine);
m_pen.setColor(Qt::black);
m_pen.setWidth(1);
painter->setPen(m_pen);
painter->drawPath(circle_path);
if(m_thetile->getProperty()->getBlocks())
{
QPainterPath circle_path;
QRect duwagrect(boundingRect().x()+2,boundingRect().y()+2,boundingRect().width()-3,boundingRect().height()-3);
circle_path.addRect(duwagrect);
m_pen.setStyle(Qt::DotLine);
m_pen.setColor(Qt::red);
m_pen.setWidth(2);
painter->setPen(m_pen);
painter->drawPath(circle_path);
}
if(this->isSelected())
{
QPainterPath circle_path;
QRect duwagrect(boundingRect().x()+2,boundingRect().y()+2,boundingRect().width()-3,boundingRect().height()-3);
circle_path.addRect(duwagrect);
m_pen.setStyle(Qt::SolidLine);
m_pen.setColor(Qt::green);
m_pen.setWidth(3);
painter->setPen(m_pen);
painter->drawPath(circle_path);
}
if(option->state & QStyle::State_MouseOver)
{
QPainterPath circle_path;
QRect duwagrect(boundingRect().x()+2,boundingRect().y()+2,boundingRect().width()-3,boundingRect().height()-3);
circle_path.addRect(duwagrect);
m_pen.setStyle(Qt::SolidLine);
m_pen.setColor(Qt::cyan);
m_pen.setWidth(2);
painter->setPen(m_pen);
painter->drawPath(circle_path);
}
}
Problem is that you are showing everything even things not needed.
You should create only visible items (items in some visible region).
Another faster approach is to create custom QGraphicsItem which paints hole map, and paint only visible tiles (no tiles as sub items).

Fastest way to draw QGraphicItems on an "equivalent" QPixmap

I want to draw colored tiles as background for a QGraphicsscene and provide pan and zoom functionality for the scene using a QGraphicsView. First I used QGraphicItems to draw each tile. Since I have many tiles this was quite a performance problem when panning or zooming but since I do not need to modify any part of the tiles afterwards I switched to generating a QPixmap using the following code:
void plotGrid(){
Plotable::GraphicItems items;
append(items,mParticleFilter.createGridGraphics());
append(items,mParticleFilter.getRoi().mRectangle.createGraphics(greenPen()));
scaleItems(items,1.0,-1.0);
QGraphicsScene scene;
showItemsOnScene(items,&scene);
QRectF boundingRect = scene.itemsBoundingRect();
double cScale = ceil(1920.0/boundingRect.size().width());
QSize size(boundingRect.size().toSize()*cScale);
QPixmap pixmap(size);
pixmap.fill(Qt::transparent);
QPainter p(&pixmap);
//p.setRenderHint(QPainter::Antialiasing);
scene.render(&p);
p.end();
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(pixmap);
item->setOffset(boundingRect.topLeft()*cScale);
item->scale(1/cScale,1/cScale);
mpView->showOnScene(item);
}
While this solves the zoom and pan problem, the time to generate the pixmap introduces some significant delay, probably because I first create a scene and then render it. Is there a faster way of producing a QPixmap on the fly starting from QGraphicItems ?
Just for completeness an image of the tiles:
So I finally got at least past using an intermediary scene. The following code only relies on a QPainter for rendering the pixmap. My main problem was to get all transformations right. Otherwise it is quite straight forward....
This version halves the processing time to 500ms in my scenario. 450ms are spent on painting the items. If someone has more suggestions for more improvement it would be most welcome (cahnging the resolution does not help much by the way)
void SceneWidget::showAsPixmap(Plotable::GraphicItems const& items){
QRectF boundingRect;
boostForeach(QGraphicsItem* pItem,items) {
boundingRect = boundingRect.united(pItem->boundingRect());
}
QSize size(boundingRect.size().toSize());
double const cMaxRes =1920;
double const scale = cMaxRes/boundingRect.size().width();
QPixmap pixmap(size*scale);
pixmap.fill(Qt::transparent);
QPainter p(&pixmap);
//p.setCompositionMode( QPainter::CompositionMode_Source );
p.translate(-boundingRect.topLeft()*scale);
p.scale(scale,scale);
QStyleOptionGraphicsItem opt;
boostForeach(QGraphicsItem* item,items) {
item->paint(&p, &opt, 0);
}
p.end();
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(pixmap);
item->scale(1.0/scale,-1.0/scale);
item->setOffset(boundingRect.topLeft()*scale);
showOnScene(item);
}

What is the fastest way to get QWidget pixel color under mouse?

I need to get the color of pixel under mouse, inside mouseMoveEvent of a QWidget (Breadboard). Currently I have this code->
void Breadboard::mouseMoveEvent(QMouseEvent *e)
{
QPixmap pixmap = QPixmap::grabWindow(winId());
QRgb color = pixmap.toImage().pixel(e->x(), e->y());
if (QColor(color) == terminalColor)
QMessageBox::information(this, "Ter", "minal");
}
Take a look at (scaled down) screenshot below-
When user moves his mouse on breadboard, the hole should get highlighted with some different color (like in red circle). And when the mouse exits, the previous color (grey) should be restored. So I need to do following steps-
Get color under mouse
According to color, floodfill the hole. (Different holes are distinguished using color)
On mouse out, restore the color. There would be wires going over holes, so I can't update the small rectangle (hole) only.
What is the fastest way of doing this? My attempt to extract color is not working i.e the Message box in my above code never displays. Moreover I doubt if my existing code is fast enough for my purpose. Remember, how fast you will be moving your mouse on breadboard.
Note - I was able to do this using wxWidgets framework. But due to some issues that project got stalled. And I am rewriting it using Qt now.
You are invited to look at code https://github.com/vinayak-garg/dic-sim
The "idiomatic" way of doing this in Qt is completely different from what you're describing. You'd use the Graphics View Framework for this type of thing.
Graphics View provides a surface for managing and interacting with a large number of custom-made 2D graphical items, and a view widget for visualizing the items, with support for zooming and rotation.
You'd define your own QGraphicsItem type for the "cells" in the breadboard that would react to hover enter/leave events by changing their color. The connections between the cells (wires, resistors, whatever) would also have their own graphics item types with the features you need for those.
Here's a quick and dirty example for you. It produces a 50x50 grid of green cells that become red when the mouse is over them.
#include <QtGui>
class MyRect: public QGraphicsRectItem
{
public:
MyRect(qreal x, qreal y, qreal w, qreal h)
: QGraphicsRectItem(x,y,w,h) {
setAcceptHoverEvents(true);
setBrush(Qt::green);
}
protected:
void hoverEnterEvent(QGraphicsSceneHoverEvent *) {
setBrush(Qt::red);
update();
}
void hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
setBrush(Qt::green);
update();
}
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QGraphicsScene scene;
for (int i=0; i<50; i++)
for (int j=0; j<50; j++)
scene.addItem(new MyRect(10*i, 10*j, 8, 8));
QGraphicsView view(&scene);
view.show();
return app.exec();
}
You could modify the hover event handlers to talk to your "main window" or "controller" indicating what's currently under the mouse so you can update your caption, legend box or tool palette.
For best speed, render only the portion of the widget you're interested in into a QPaintDevice (like a QPixmap). Try something like this:
void Breadboard::mouseMoveEvent(QMouseEvent *e)
{
// Just 1 pixel.
QPixmap pixmap(1, 1);
// Target coordinates inside the pixmap where drawing should start.
QPoint targetPos(0, 0);
// Source area inside the widget that should be rendered.
QRegion sourceArea( /* use appropriate coordinates from the mouse event */ );
// Render it.
this->render(&pixmap, targetPos, sourceArea, /* look into what flags you need */);
// Do whatever else you need to extract the color from the 1 pixel pixmap.
}
Mat's answer is better if you're willing to refactor your application to use the graphics view API.