Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Qt QGraphicsPathItem example 1: basic

 

QGraphicsPathItem example 1: basic is a QGraphicsPathItem example. This example shows how to draw some selectable and movable QGraphicsPathItem.

 

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppQGraphicsPathItemExample1.pro

 

QT       += core gui
QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Werror
TARGET = CppQGraphicsPathItemExample1
TEMPLATE = app

SOURCES += \
    qtmain.cpp \
    qtwidget.cpp \
    qtitem.cpp

HEADERS += \
    qtwidget.h \
    qtitem.h

 

 

 

 

 

qtitem.h

 

#ifndef QTITEM_H
#define QTITEM_H

#include <QGraphicsPathItem>

struct QtItem : public QGraphicsPathItem
{
  QtItem(QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);
};

#endif // QTITEM_H

 

 

 

 

 

qtitem.cpp

 

#include <QPainter>
#include "qtitem.h"

QtItem::QtItem(
  QGraphicsItem *parent, QGraphicsScene *scene)
  : QGraphicsPathItem(parent,scene)
{
  this->setFlags(
      QGraphicsItem::ItemIsSelectable
    | QGraphicsItem::ItemIsMovable);

  //Set a simple path
  QPainterPath path;
  path.quadTo(100,0,100,100);
  this->setPath(path);
}

 

 

 

 

 

qtmain.cpp

 

#include <QApplication>
#include <QDesktopWidget>
#include "qtwidget.h"

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  QtWidget w;
  {
    //Resize the dialog and put it in the screen center
    w.setGeometry(0,0,600,400);
    const QRect screen = QApplication::desktop()->screenGeometry();
    w.move( screen.center() - w.rect().center() );
  }
  w.show();
  return a.exec();
}

 

 

 

 

 

qtwidget.h

 

#ifndef QTWIDGET_H
#define QTWIDGET_H

#include <QGraphicsView>

///The widget holding the items
struct QtWidget : public QGraphicsView
{
  QtWidget(QWidget *parent = 0);
};

#endif // QTWIDGET_H

 

 

 

 

 

qtwidget.cpp

 

#include <cassert>
#include <QGraphicsScene>
#include "qtitem.h"
#include "qtwidget.h"

QtWidget::QtWidget(QWidget *parent)
  : QGraphicsView(new QGraphicsScene,parent)
{
  const int n_items = 16;
  for (int i=0; i!=n_items; ++i)
  {
    const double angle = 2.0 * M_PI * (static_cast<double>(i) / static_cast<double>(n_items));
    const double x1 =  std::sin(angle) * 100.0;
    const double y1 = -std::cos(angle) * 100.0;
    QtItem * const item = new QtItem;
    item->setPos(x1,y1);
    scene()->addItem(item);
  }
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml