I just started learning qt widgets and C++ in general, so I don't understand a lot. I created a regular project, made a full-screen view, created a scene inside it, and set a square inside the scene. I wanted to set view, scene, rect to different colors, but for some reason I can't do it. I either have the entire view painted in the color of the scene or vice versa
1)main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
2)mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsItem>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
};
#endif // MAINWINDOW_H
3)mainwindow.cpp
#include "mainwindow.h"
#include <QGraphicsRectItem>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
// Create QGraphicsScene
QGraphicsScene *scene = new QGraphicsScene(this);
// Set the scene size (in this case, for example, 300x300)
scene->setSceneRect(0, 0, 300, 300);
// Installing a brush (color lantern) for scenes
scene->setBackgroundBrush(QBrush(Qt::green));
// We create a QGraphicsRectItem (a rectangle with the boundaries of the scene) and deliver it to the case
QGraphicsRectItem *sceneBounds = new QGraphicsRectItem(scene->sceneRect());
scene->addItem(sceneBounds);
// Create a QGraphicsRectItem (rectangle) and add it to the scene
QGraphicsRectItem *rectangleItem = new QGraphicsRectItem(50, 50, 100, 100);
scene->addItem(rectangleItem);
// Set the brush (the color is filled) for the outline
rectangleItem->setBrush(QBrush(Qt::yellow));
// Create a QGraphicsView and set the danger to it
QGraphicsView *view = new QGraphicsView(scene);
// Set the background color for QGraphicsView (can be any color that does not affect the case)
view->setBackgroundBrush(QBrush(Qt::lightGray));
// Set the scene alignment in the upper left corner
view->setAlignment(Qt::AlignLeft | Qt::AlignTop);
// Set QGraphicsView as the central widget of the main window
setCentralWidget(view);
}
MainWindow::~MainWindow() {}