Trying to use boundingRect in Qt - c++

What is wrong with class Kwadrat? I have an error:
Invalid new-expression of abstract class type 'Kwadrat'
Kwadrat* kwadrat = new Kwadrat(20);
I want a moving square on the screen (when it hit 370 on X or 370 on Y coordinate it comes back to middle).
when Kwadrat is classic QGraphicsRectItem I have a bug with (0,0) coordinate.
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QPixmap>
#include "poruszanie.h"
#include <QRectF>
#include <QGraphicsRectItem>
class Kwadrat : public QGraphicsItem
{
Q_OBJECT
public:
Kwadrat(int size)
: QGraphicsItem(NULL) // we could parent, but this may confuse at first
{
m_boundingRect = QRectF(0, 0, size, size);
}
QRectF boundingRect() const
{
return m_boundingRect;
}
private:
QRectF m_boundingRect;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene*scena=new QGraphicsScene();
// Poruszanie*kwadrat=new Poruszanie();
// kwadrat->setRect(0,0,20,20);
// kwadrat->setBrush(QBrush(Qt::white));
// scena->addItem(kwadrat);
Kwadrat*kwadrat=new Kwadrat(20);
kwadrat->setBrush(QBrush(Qt::white));
scena->addItem(kwadrat);
kwadrat->setFlag(QGraphicsItem::ItemIsFocusable);
kwadrat->setFocus();
QGraphicsView *widok=new QGraphicsView(scena);
widok->setBackgroundBrush(QBrush(Qt::yellow));
widok->setMinimumSize(400,400);
widok->show();
return a.exec();
}

To write your own graphics item, you first create a subclass of
QGraphicsItem, and then start by implementing its two pure virtual
public functions: boundingRect(), which returns an estimate of the
area painted by the item, and paint(), which implements the actual
painting.
From http://doc.qt.io/qt-5/qgraphicsitem.html#details
So you need to implement the pure virtual function paint to do the painting of your QGraphicsItem to get rid of the error, your compiler should have shown that, besides telling you that your class is abstract (because of the missing function implementation).

Related

Qt crashes when trying to use static QGraphicsScene, QGraphicsView

I am trying to create a singleton game window class that I can use to add other items later on (such as player, enemy, bullet etc). This is the code:
#ifndef GAMEWINDOW_H
#define GAMEWINDOW_H
#include <QGraphicsScene>
#include <QGraphicsView>
class GameWindow {
public:
GameWindow();
static QGraphicsScene* scene();
static QGraphicsView* view();
private:
static QGraphicsScene* m_scene;
static QGraphicsView* m_view;
};
#endif // GAMEWINDOW_H
#include "gamewindow.h"
QGraphicsScene* GameWindow::m_scene = new QGraphicsScene(0, 0, 800, 600);
QGraphicsView* GameWindow::m_view = new QGraphicsView(m_scene);
GameWindow::GameWindow() {
m_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_view->setFixedSize(800,600);
m_view->setBackgroundBrush(QBrush(QImage(":/images/space.png")));
m_view->show();
}
QGraphicsScene* GameWindow::scene() { return m_scene; }
QGraphicsView* GameWindow::view() { return m_view; }
// main.cpp
#include <QApplication>
#include "gamewindow.h"
int main(int argc, char* argv[]){
QApplication a(argc, argv);
// launch the game window
GameWindow win;
return a.exec();
}
But for some reason, the application crashes, and the compile output does not give any hints on why. It just says that the process exited normally. How can I solve this, or is this a stupid idea? I'm open to suggestions on alternative solutions.
I didn't know what to try, because my understanding of the underlying problem is very limited.

"QPainter::drawRects: Painter not active " error C++/QT

I'm a beginner at Qt
and c++ and I wanted to see how to use a QPainter and events in Qt but I got stuck because of an error message during the execution, my original code:
the main.cpp
#include "customwidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QScopedPointer<QWidget> widget(new customWidget());
widget->resize(240, 120);
widget->show();
return a.exec();
}
and the header:
#ifndef CUSTOMWIDGET_H
#define CUSTOMWIDGET_H
#include <QWidget>
#include <QMouseEvent>
#include <QPoint>
#include <QPainter>
class customWidget : public QWidget
{
Q_OBJECT
public:
explicit customWidget(QWidget *parent = 0);
void paintEvent(QPaintEvent *);
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
private:
QPoint m_mousePos;
QRect m_r2;
signals:
void needToRepaint();
public slots:
};
#endif // CUSTOMWIDGET_H
and the .cpp:
#include "customwidget.h"
customWidget::customWidget(QWidget *parent) : QWidget(parent)
{
QRect m_r2;
QPoint m_mousePos;
QObject::connect(this, SIGNAL(needToRepaint()), this, SLOT(repaint()));
}
void customWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
// ############ First Rectangle ****************************************
QRect r1 = rect().adjusted(10, 10, -10, -10);
painter.setPen(QColor("#FFFFFF"));
painter.drawRect(r1);
// ############ Seconde Rectangle ****************************************
QRect r2(QPoint(0, 0), QSize(100, 100));
m_r2.moveCenter(m_mousePos);
QPainter painter2;
QPen pen;
painter2.setPen(QColor("#000000"));
pen.setWidth(3);
painter2.setPen(pen);
painter2.drawRect(m_r2);
update();
}
void customWidget::mouseMoveEvent(QMouseEvent *event)
{
m_mousePos = event->pos();
emit needToRepaint();
}
I tried to search it on the web and saw that it's because the QPainter isn't located in the paintEvent but it's not the case in my code, thanks for your help.
You only need one painter. The second one wasn't activated, and you don't need it anyway.
Don't ever call repaint() unless you somehow absolutely need the painting to be done before repaint() returns (that's what happens!). If you keep the event loop running properly, you won't ever need that.
Don't call update() from paintEvent(): it's nonsense (literally).
When you wish to repaint the widget, call update(): it schedules an update from the event loop. Multiple outstanding updates are coalesced to keep the event loop functional and prevent event storms.
Let the compiler generate even more memory management code for you. You've done the first step by using smart pointers - that's good. Now do the second one: hold the instance of CustomWidget by value. It doesn't have to be explicitly dynamically allocated. C++ is not C, you can leverage values.
In a simple test case, you don't want three files. Your code should fit in as few lines as possible, in a single main.cpp. If you need to moc the file due to Q_OBJECT macros, add #include "main.moc" at the end, and re-run qmake on the project to take notice of it.
This is how such a test case should look, after fixing the problems. Remember: it's a test case, not a 100kLOC project. You don't need nor want the meager 35 lines of code spread across three files. Moreover, by spreading out the code you're making it harder for yourself to comprehend.
Even in big projects, unless you can show significant build time improvements if doing the contrary, you can have plenty of small classes implemented Java-style completely in the header files. That's about the only Java-style-anything that belongs in C++.
// https://github.com/KubaO/stackoverflown/tree/master/questions/simple-paint-38796140
#include <QtWidgets>
class CustomWidget : public QWidget
{
QPoint m_mousePos;
public:
explicit CustomWidget(QWidget *parent = nullptr) : QWidget{parent} {}
void paintEvent(QPaintEvent *) override;
void mouseMoveEvent(QMouseEvent *event) override {
m_mousePos = event->pos();
update();
}
};
void CustomWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
auto r1 = rect().adjusted(10, 10, -10, -10);
painter.setPen(Qt::white);
painter.drawRect(r1);
auto r2 = QRect{QPoint(0, 0), QSize(100, 100)};
r2.moveCenter(m_mousePos);
painter.setPen(QPen{Qt::black, 3, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin});
painter.drawRect(r2);
}
int main(int argc, char ** argv) {
QApplication app{argc, argv};
CustomWidget w;
w.show();
return app.exec();
}
This error can happen too when the QPixmap used to create the QPainter(QPixmap) is invalid (if there is no file at such path).
Be sure your QPixmap is correct before painting on it.

QML: How to call method from a C++ subclass?

I have two C++ classes (TrafficLight and Light). Light is a child of TrafficLight. QML can see everything from TrafficLight and nothing from Light, for example...I get the following error when I try to access a method from Light like TrafficLight.get_light(0).get_color()
TypeError: Cannot call method 'get_color' of undefined
I exposed my parent class (TrafficLight) to qml (see main below). I assumed it would expose the subclass inside it, as well...but apparently not.
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "traffic_light.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Traffic_Light traffic_light;
engine.rootContext()->setContextProperty("TrafficLight", &traffic_light);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
My question is how would I expose the subclass? I can't just create an instance of Light and expose it the same way I did TrafficLight. Reason being is it won't be the same Light that's inside the TrafficLight. :(
light.h
#ifndef LIGHT_H
#define LIGHT_H
#include <QDebug>
#include <QObject>
enum Color
{
RED = 0,
YELLOW,
GREEN
};
class Light : public QObject{
Q_OBJECT
public:
Light();
public slots:
void set_color(Color color);
int get_color();
void set_light(bool is_on);
bool get_light();
private:
Color m_color;
bool m_light_on;
};
#endif // LIGHT_H
traffic_light.h
#ifndef TRAFFIC_LIGHT_H
#define TRAFFIC_LIGHT_H
#include <QDebug>
#include <QObject>
#include <QTimer>
#include "light.h"
class Traffic_Light : public QObject
{
Q_OBJECT
public:
Traffic_Light();
public slots:
Light &get_light(int index);
void toggle_light(int index);
private:
Light m_light[3];
};
#endif // TRAFFIC_LIGHT_H

qt openGL - draw triangle

So my goal is to (first) draw a triangle with openGL.
my questions:
1) How/when do both of my functions get called? I see that only one gets called. i.e. void MyGLWidget::paintGL. I am confused because as you can see I never call this function, it gets called automatically.I added a widget on my ui which I promoted to MyGLWidget. But when/why/how does it get (not) called?
my code:
myglwidget.cpp
#include "myglwidget.h"
#include <QtWidgets>
#include <QtOpenGL>
#include <GL/glu.h>
MyGLWidget::MyGLWidget(QWidget *parent)
: QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
{
}
void MyGLWidget::initializeGL()
{
glClearColor(1,1,0,1);
qDebug("init"); //<-------never gets printed
}
void MyGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
qDebug("painting"); //<---- does get printed
glColor3f(1,0,0);
glBegin(GL_TRIANGLES);
glVertex3f(-0.5,-0.5,0);
glVertex3f(0.5,-0.5,0);
glVertex3f(0.0,0.5,0);
glEnd();
}
myglwidget.h
#ifndef MYGLWIDGET_H
#define MYGLWIDGET_H
#include <QGLWidget>
class MyGLWidget : public QGLWidget
{
Q_OBJECT
public:
explicit MyGLWidget(QWidget *parent = 0);
void initializeGL();
void paintGL();
void resizeGL(int width, int height);
private:
};
#endif // MYGLWIDGET_H
main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.setWindowTitle("OpenGL with Qt DAO");
w.show();
return a.exec();
}
I do not see a class called Widget made by you which is connected to the class MyGlWidget. Maybe I am wrong but shouldn't you have to make a instance of MyGlWidget (Call it's constructor instead of Widget?)
Both functions are called internally by the QGLWidget super class. See QT Docs
In the documentation you also see that these virtual functions are protected. In your code they are public. So you have to change that in order to make it work.

QT drawing without erasing widget

I have a QWidget-derived class. In the constructor I say:
setPalette(QPalette(QColor(250,250,200)));
setAutoFillBackground(true);
Then in my widget's paintEvent() I say:
QPainter painter(this);
painter.drawRect(1,2,3,4);
There is also an updateNow() slot...which just calls update(). How can I make sure my palette doesn't get erased after that update call?
I don't have any problems with the following:
#include <QApplication>
#include <QWidget>
#include <QPalette>
#include <QPaintEvent>
#include <QPainter>
class Test : public QWidget
{
public:
Test()
{
setPalette(QPalette(QColor(250, 250, 200)));
setAutoFillBackground(true);
}
protected:
virtual void paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.drawRect(10, 20, 30, 40);
}
virtual void mousePressEvent(QMouseEvent*)
{
update();
}
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Test myTest;
myTest.show();
return app.exec();
}
The rectangle draws, and stays after I click, which triggers update. What are you seeing?