Game Programming using Qt 5 Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – Creating a project with a Graphics View

Let's put all these components together in a minimalistic project. From the Welcome screen, click on the New Project button and select Qt Widgets Application again. Name the project graphics_view_demo, select the correct kit, uncheck the Generate form checkbox, and finish the wizard. We don't actually need the MainWindow class that was generated for us, so let's delete it from the project. In the project tree, locate mainwindow.h and select Remove file in the context menu. Enable the Delete file permanently checkbox and click on OK. This will result in deleting the mainwindow.h file from the disk and removing its name from the graphics_view_demo.pro file. If the file was open in Qt Creator, it will suggest that you close it. Repeat the process for mainwindow.cpp.

Open the main.cpp file, remove #include "mainwindow.h", and write the following code:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene scene;
    QGraphicsRectItem *rectItem = 
new QGraphicsRectItem(QRectF(0, 0, 100, 50)); scene.addItem(rectItem); QGraphicsEllipseItem *circleItem = new QGraphicsEllipseItem(QRect(0, 50, 25, 25)); scene.addItem(circleItem); QGraphicsSimpleTextItem *textItem = new QGraphicsSimpleTextItem(QObject::tr("Demo")); scene.addItem(textItem); QGraphicsView view(&scene); view.show(); return a.exec(); }

When you run the project, you should get the following result: