Exemple #1
0
int main(int argc, char **argv) {
  QApplication app( argc, argv );
  QGraphicsScene scene;
  QGraphicsView view(&scene);
  view.setBackgroundBrush(QBrush(Qt::black));
  view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
  view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
  view.setDragMode(QGraphicsView::ScrollHandDrag);
  view.show();
  // view.showFullScreen();

  QGraphicsRectItem *r = scene.addRect(-50, -50, 10, 10);
  r->setPen(QPen(QColor(255, 0, 0)));
  r->setBrush(QBrush(QColor(0, 255, 0)));
  r->show();
  r = scene.addRect(0, 0, 10, 10);
  r->setPen(QPen(QColor(255, 0, 0)));
  r->setBrush(QBrush(QColor(0, 255, 0)));
  r->show();
  r = scene.addRect(200, 200, 10, 10);
  r->setPen(QPen(QColor(255, 0, 0)));
  r->setBrush(QBrush(QColor(0, 255, 0)));
  r->show();

  scene.setSceneRect(-100, -100, 100, 100);
  view.resize(200, 200);
  return app.exec();
}
Exemple #2
0
void FadeMessage::setupScene()
{
    QGraphicsRectItem *parent = m_scene.addRect(0, 0, 800, 600);
    parent->setPen(Qt::NoPen);
    parent->setZValue(0);

    QGraphicsPixmapItem *bg = m_scene.addPixmap(QPixmap(":/background.jpg"));
    bg->setParentItem(parent);
    bg->setZValue(-1);

    for (int i = 1; i < 5; ++i)
        for (int j = 2; j < 5; ++j) {
            QGraphicsRectItem *item = m_scene.addRect(i * 50, (j - 1) * 50, 38, 38);
            item->setParentItem(parent);
            item->setZValue(1);
            int hue = 12 * (i * 5 + j);
            item->setBrush(QColor::fromHsv(hue, 128, 128));
        }

    QFont font;
    font.setPointSize(font.pointSize() * 2);
    font.setBold(true);
    QFontMetrics fontMetrics(font);
    int fh = fontMetrics.height();

    QString sceneText = "Qt Everywhere!";
    int sceneTextWidth = fontMetrics.width(sceneText);

    QGraphicsRectItem *block = m_scene.addRect(50, 300, sceneTextWidth, fh + 3);
    block->setPen(Qt::NoPen);
    block->setBrush(QColor(102, 153, 51));

    QGraphicsTextItem *text = m_scene.addText(sceneText, font);
    text->setDefaultTextColor(Qt::white);
    text->setPos(50, 300);
    block->setZValue(2);
    block->hide();

    text->setParentItem(block);
    m_message = block;

    m_effect = new QGraphicsColorizeEffect;
    m_effect->setColor(QColor(122, 193, 66));
    m_effect->setStrength(0);
    m_effect->setEnabled(true);
    parent->setGraphicsEffect(m_effect);

    QPushButton *press = new QPushButton;
    press->setText(tr("Press me"));
    connect(press, SIGNAL(clicked()), SLOT(togglePopup()));
    m_scene.addWidget(press);

#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
    press->move(200, 210);
#else
    press->move(300, 500);
#endif
}
Exemple #3
0
void MyScene::changeTileColor(int index) {

    if(rects[index] == NULL) {   // so index does not exist

        int rectX = index % (width/11);
        int rectY = floor(index / (width/11));

        // create new object
        QGraphicsRectItem *tempRectItem = new QGraphicsRectItem(rectX*11 + 1, rectY*11+1, 9, 9);
        tempRectItem->setBrush(QBrush(*light));   // default color is white
        tempRectItem->setPen(QPen(*light));

        rects[index] = tempRectItem;

        /* when item is added ones to the scene it is possible to change it properties
         * without adding it again and agian
        */
        addItem(rects[index]);

    } else {
        // code change tile color depend on current color
        if(rects[index]->brush().color() == *light) {
            rects[index]->setBrush(QBrush(*dark));
            rects[index]->setPen(QPen(*dark));
        } else {
            rects[index]->setBrush(QBrush(*light));
            rects[index]->setPen(QPen(*light));
        }
    }
}
void ShapeFormulaNode::AddFillRect(qreal x, qreal y, qreal width, qreal height, QColor& color)
{
	QGraphicsRectItem* i = new QGraphicsRectItem(x, y, width, height, item);
	i->setBrush(QBrush(color));
	i->setPen(QPen(color));
	((QGraphicsItemGroup*)item)->addToGroup(i);
}
void DivePictureItem::setPixmap(const QPixmap &pix)
{
	DivePixmapItem::setPixmap(pix);
	QRectF r = boundingRect();
	QGraphicsRectItem *rect = new QGraphicsRectItem(0 - 10, 0 -10, r.width() + 20, r.height() + 20, this);
	rect->setPen(Qt::NoPen);
	rect->setBrush(QColor(Qt::white));
	rect->setFlag(ItemStacksBehindParent);
	rect->setZValue(-1);

	QGraphicsRectItem *shadow = new QGraphicsRectItem(rect->boundingRect(), this);
	shadow->setPos(5,5);
	shadow->setPen(Qt::NoPen);
	shadow->setBrush(QColor(Qt::lightGray));
	shadow->setFlag(ItemStacksBehindParent);
	shadow->setZValue(-2);
}
Exemple #6
0
 /**
  * Creates the decoration point.
  * @param p        base point to decorate
  * @param parent   parent item
  * @return         decoration point
  */
 QGraphicsRectItem* decoratePoint(const QPointF &p, QGraphicsItem* parent)
 {
     const qreal SIZE = 4.0;
     const qreal SIZE_HALF = SIZE / 2.0;
     QGraphicsRectItem *rect = new QGraphicsRectItem(p.x() - SIZE_HALF,
                                                     p.y() - SIZE_HALF,
                                                     SIZE, SIZE,
                                                     parent);
     rect->setBrush(QBrush(Qt::blue));
     rect->setPen(QPen(Qt::blue));
     return rect;
 }
QGraphicsRectItem* ScreenGrabberChooserRectItem::createHandleItem(QGraphicsScene* scene)
{
    QGraphicsRectItem* handle = new QGraphicsRectItem(0, 0, HandleSize, HandleSize);
    handle->setPen(QPen(Qt::blue));
    handle->setBrush(Qt::NoBrush);

    scene->addItem(handle);
    addToGroup(handle);

    handle->installSceneEventFilter(this);
    return handle;
}
Exemple #8
0
void MemoryTracePane::addStackFrame(int numCells)
{
    QPen pen(Qt::black);
    pen.setWidth(4);
    QGraphicsRectItem *item = new QGraphicsRectItem(stackLocation.x() - 2, stackLocation.y() + MemoryCellGraphicsItem::boxHeight, 
                      static_cast<qreal>(MemoryCellGraphicsItem::boxWidth + 4),
                      static_cast<qreal>(MemoryCellGraphicsItem::boxHeight * numCells), 0);
    item->setPen(pen);
    graphicItemsInStackFrame.push(item);
    isStackFrameAddedStack.push(false);
    item->setZValue(1.0); // This moves the stack frame to the front
    numCellsInStackFrame.push(numCells);
}
Exemple #9
0
void ViewScene::drawTile(r2d2::Box box,QColor color){
    QRectF tempRect = box_tile_2_qrect(box);
    QGraphicsRectItem *block = new QGraphicsRectItem;
    block->setBrush(* new QBrush(color));
    //check current draw outline state
    if(!outlined){
        block->setPen(Qt::NoPen);
    }
    block->setRect(0,0,tempRect.width(),tempRect.height());
    block->setPos(tempRect.x(),tempRect.y());
    block->setVisible(true);
    addItem(block);
}
Exemple #10
0
void MemoryTracePane::addHeapFrame(int numCells)
{
    QPen pen(Qt::black);
    pen.setWidth(4);
    QGraphicsRectItem *item = new QGraphicsRectItem(heapLocation.x() - 2,
                                                    heapLocation.y() - MemoryCellGraphicsItem::boxHeight * (numCells - 1),
                      static_cast<qreal>(MemoryCellGraphicsItem::boxWidth + 4),
                      static_cast<qreal>(MemoryCellGraphicsItem::boxHeight * numCells), 0);
    item->setPen(pen);
    heapFrameItemStack.push(item);
    isHeapFrameAddedStack.push(false);
    item->setZValue(1.0); // This moves the heap frame to the front
}
Exemple #11
0
void TileScene::DrawEraserPreview(int x, int y)
{
    QGraphicsRectItem *rect = new QGraphicsRectItem(x * tileController->GetTileWidth(),
                           y * tileController->GetTileHeight(),
                           tileController->GetTileWidth(),
                           tileController->GetTileHeight());

    rect->setBrush(QBrush(QColor(0, 0, 255, 0x80)));
    rect->setPen(QPen(Qt::transparent));

    addItem(rect);
    eraserPreviewItems.append(rect);
}
void MainWindow::slotAddRectItem()      //在场景中加入一个长方形图元
{
    QGraphicsRectItem *item = new QGraphicsRectItem(QRectF(0,0,60,60));
    QPen pen;
    pen.setWidth(3);
    pen.setColor(QColor(qrand()%256,qrand()%256,qrand()%256));
    item->setPen(pen);
    item->setBrush(QColor(qrand()%256,qrand()%256,qrand()%256));
    item->setFlag(QGraphicsItem::ItemIsMovable);

    scene->addItem(item);
    item->setPos((qrand()%int(scene->sceneRect().width()))-200,(qrand()%int(scene->sceneRect().height()))-200);
}
Exemple #13
0
void TerrainProfileGraph::drawSelectionBox(double position)
{
  if (_selecting && _selectStart != position)
  {
    double selectionMin = osg::minimum(_selectStart, position);
    double selectionMax = osg::maximum(_selectStart, position);
    QGraphicsRectItem* selectionBox = new QGraphicsRectItem(selectionMin, _graphField.y(), selectionMax - selectionMin, _graphField.height());
    selectionBox->setPen(QPen(Qt::NoPen));
    selectionBox->setBrush(QBrush(QColor(0, 0, 0, 64)));
    selectionBox->setZValue(OVERLAY_Z);
    selectionBox->setParentItem(_hoverLine);
  }
}
Exemple #14
0
void BbScene::testAddRect()
{
	QGraphicsRectItem* item = new QGraphicsRectItem;

	QPen thePen = BbUtil::createPen(5, Qt::red);
	item->setPen(thePen);

	double ww = getPageWidth() - 20;
	double hh = getPageHeight() - 20;
	QRectF theRect(-ww / 2, -hh / 2, ww, hh);
	item->setRect(theRect);

	addItem(item);	
}
Exemple #15
0
void TetrisCup::drawOnScene(QGraphicsScene &_scene)
{
    _scene.addItem(new QGraphicsRectItem(-1, -1, BRICK * m_width + 2, BRICK * m_height + 2));

    for (int i = 0; i < m_content.getHeight(); ++i)
        for (int j = 0; j < m_content.getWidth(); j++) {
            if (m_content.getValue(j, i) == 1) {
                QGraphicsRectItem *rect = new QGraphicsRectItem(j * BRICK, i * BRICK, BRICK, BRICK);
                rect->setPen(QPen(QBrush(QColor(Qt::lightGray)), 1, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin));
                rect->setBrush(QBrush(QColor(Qt::darkGray)));
                _scene.addItem(rect);
            }
        }
}
Exemple #16
0
void VisualNavbar::drawMetadata(QList<MappedSegmentMetadata> metadata,
                                RVA offset,
                                double x,
                                double width_per_byte,
                                double h, QColor color)
{
    for (auto s : metadata) {
        double block_x = x + ((double)(s.address - offset) * width_per_byte);
        double block_width = (double)s.size * width_per_byte;
        QGraphicsRectItem *rect = new QGraphicsRectItem(block_x, 0, block_width, h);
        rect->setPen(Qt::NoPen);
        rect->setBrush(QBrush(color));
        graphicsScene->addItem(rect);
    }
}
Exemple #17
0
void tst_QGraphicsEffect::colorize()
{
    if (qApp->desktop()->depth() < 24) {
        QSKIP("Test only works on 32 bit displays", SkipAll);
        return;
    }

    QGraphicsScene scene(0, 0, 100, 100);

    QGraphicsRectItem *item = scene.addRect(0, 0, 50, 50);
    item->setPen(Qt::NoPen);
    item->setBrush(QColor(122, 193, 66)); // Qt light green

    QGraphicsColorizeEffect *effect = new QGraphicsColorizeEffect;
    effect->setColor(QColor(102, 153, 51)); // Qt dark green
    item->setGraphicsEffect(effect);

    QPainter painter;
    QImage image(100, 100, QImage::Format_ARGB32_Premultiplied);

    image.fill(0);
    painter.begin(&image);
    painter.setRenderHint(QPainter::Antialiasing);
    scene.render(&painter);
    painter.end();

    QCOMPARE(image.pixel(10, 10), qRgb(191, 212, 169));

    effect->setStrength(0.5);

    image.fill(0);
    painter.begin(&image);
    painter.setRenderHint(QPainter::Antialiasing);
    scene.render(&painter);
    painter.end();

    QCOMPARE(image.pixel(10, 10), qRgb(156, 203, 117));

    effect->setStrength(0.0);

    image.fill(0);
    painter.begin(&image);
    painter.setRenderHint(QPainter::Antialiasing);
    scene.render(&painter);
    painter.end();

    QCOMPARE(image.pixel(10, 10), qRgb(122, 193, 66));
}
Exemple #18
0
//-----------------------------------------------------------------------------
// Function: StickyNote::createGluedEdge()
//-----------------------------------------------------------------------------
void StickyNote::createGluedEdge()
{
    QColor topColor = QColor("lemonChiffon").darker(103);

    QGraphicsRectItem* glueEdge = new QGraphicsRectItem(0, 0, DEFAULT_WIDTH, TOP_OFFSET);
    QPen outlinePen(Qt::black, 0, Qt::NoPen);
    glueEdge->setPen(outlinePen);
    glueEdge->setBrush(topColor);

    addToGroup(glueEdge);

    timeLabel_ = new QGraphicsSimpleTextItem();
    timeLabel_->setBrush(Qt::gray);
    timeLabel_->setPos(5, TOP_OFFSET/2 - QFontMetrics(timeLabel_->font()).height()/2);
    addToGroup(timeLabel_);
}
QGraphicsItem * EnvelopeClient::createGraphicsItem()
{
    int padding = 4;
    QGraphicsRectItem *item = new QGraphicsRectItem();
    ParameterGraphicsItem *parameterItem = new ParameterGraphicsItem(this);
    QRectF rect = QRect(0, 0, 1200, 420);
    rect = rect.translated(parameterItem->boundingRect().width() + 2 * padding, padding);
    parameterItem->setPos(padding, padding);
    parameterItem->setParentItem(item);
    EnvelopeGraphicsItem *ourItem = new EnvelopeGraphicsItem(rect, this, item);
    item->setRect((rect | parameterItem->boundingRect().translated(parameterItem->pos())).adjusted(-padding, -padding, padding, padding));
    item->setPen(QPen(QBrush(Qt::black), 1));
    item->setBrush(QBrush(Qt::white));
    QObject::connect(this, SIGNAL(changedYSteps(int)), ourItem, SLOT(setHorizontalSlices(int)));
    return item;
}
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
QGraphicsItem *Rectangle::createGraphicsItem()
{
    QGraphicsRectItem *rect = new QGraphicsRectItem(QRectF(QPointF(_x1,_y1),QPointF(_x2,_y2)));

    QPen pen;
    pen.setColor(_color);
    pen.setWidth(0);
    rect->setPen(pen);

    QBrush brush;
    brush.setStyle(Qt::SolidPattern);
    brush.setColor(_color);
    rect->setBrush(brush);

    return rect;
}
Exemple #21
0
PortGraphicsItem::PortGraphicsItem(QPointF position,
                                   DocumentEntry* relatedEntry,
                                   model::enums::PortDirection direction)
    : SchematicElement(position, relatedEntry) {
    // Ports are measured from the center, not the upper left corner

    QAbstractGraphicsShapeItem* newActual;

    m_direction = direction;
    // select the Pen and Brush based on the Port direction
    switch (direction) {
    case model::enums::PortDirection::IN:
        newActual = factories::GIFactory::createPortAdapterGI();
        this->m_defaultPen = PEN_INPUT_PORT;
        this->m_defaultBrush = BRUSH_INPUT_PORT;
        this->setAcceptDrops(true); // input ports can receive wire drops
        this->setAcceptedMouseButtons(0); // no way to click that
        break;
    case model::enums::PortDirection::OUT:
        newActual = factories::GIFactory::createPortAdapteeGI();
        this->m_defaultPen = PEN_OUTPUT_PORT;
        this->m_defaultBrush = BRUSH_OUTPUT_PORT;
        this->setAcceptedMouseButtons(Qt::LeftButton); // output ports can be dragged from
        break;
    default:
        newActual = factories::GIFactory::createPortInvalidGI();
        this->m_defaultPen = PEN_UNDEFINED_PORT;
        this->m_defaultBrush = BRUSH_UNDEFINED_PORT;
        break;
    }
    Q_CHECK_PTR(newActual);

    newActual->setPen(this->m_defaultPen);
    newActual->setBrush(this->m_defaultBrush);
    this->addActual(newActual);

    qreal r = (qreal)PORT_RADIUS;
    QGraphicsRectItem* background = new QGraphicsRectItem(-r, -r, 2 * r, 2 * r, this);
    background->setBrush(PORT_BACKGROUND_BRUSH);
    background->setPen(PORT_BACKGROUND_PEN);
    background->setZValue(-2);
    this->addActual(background);

    Q_ASSERT(this->actual()->isVisible());
    this->setAcceptHoverEvents(true);
}
Exemple #22
0
void ViewerWidget::load(const QByteArray &data)
{
    scene->clear();
    QList<QGraphicsItem *> items;
    QPixmap pixmap;
    if (pixmap.loadFromData(data)) {
        items << new QGraphicsPixmapItem(pixmap);
    }
    else if (data.startsWith("%PDF")) {
        fz_stream *stream = fz_open_memory(context, (unsigned char *)data.constData(), data.length());
        fz_document *doc = fz_open_document_with_stream(context, ".pdf", stream);
        fz_close(stream);
        int pagecount = fz_count_pages(doc);
        for (int i = 0; i < pagecount; i++) {
            fz_page *page = fz_load_page(doc, i);
            fz_rect bounds;
            fz_bound_page(doc, page, &bounds);
            fz_display_list *list = fz_new_display_list(context);
            fz_device *dev = fz_new_list_device(context, list);
            fz_run_page(doc, page, dev, &fz_identity, NULL);
            fz_free_device(dev);
            fz_free_page(doc, page);
            PageItem *item = new PageItem(context, list, bounds.x1 - bounds.x0, bounds.y1 - bounds.y0);
            item->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
            items << item;
        }
        fz_close_document(doc);
    } else {
        scene->setSceneRect(0, 0, 0, 0);
        return;
    }
    int top = 0;
    QPen outline(Qt::lightGray, 2, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
    outline.setCosmetic(true);
    foreach (QGraphicsItem *item, items) {
        QGraphicsRectItem *rim = new QGraphicsRectItem(item->boundingRect());
        item->setPos(0, top);
        rim->setPos(0, top);
        rim->setPen(outline);
        rim->setBrush(Qt::NoBrush);
        scene->addItem(rim);
        scene->addItem(item);
        top += item->boundingRect().height() + SPACING;
    }
Exemple #23
0
void fillItemFromRectangle(QGraphicsItemGroup *item, const CLBoundingBox *pBB, const CLRectangle *pRect, const CLGroup *group, const CLRenderResolver* resolver)
{
  double x = pBB->getPosition().getX() + pRect->getX().getAbsoluteValue() + pRect->getX().getRelativeValue() / 100.0 * pBB->getDimensions().getWidth();
  double y = pBB->getPosition().getY() + pRect->getY().getAbsoluteValue() + pRect->getY().getRelativeValue() / 100.0 * pBB->getDimensions().getHeight();
  double w = pRect->getWidth().getAbsoluteValue() + pRect->getWidth().getRelativeValue() / 100.0 * pBB->getDimensions().getWidth();
  double h = pRect->getHeight().getAbsoluteValue() + pRect->getHeight().getRelativeValue() / 100.0 * pBB->getDimensions().getHeight();
  double rx = pRect->getRadiusX().getAbsoluteValue() + pRect->getRadiusX().getRelativeValue() / 100.0 * pBB->getDimensions().getWidth();
  double ry = pRect->getRadiusY().getAbsoluteValue() + pRect->getRadiusY().getRelativeValue() / 100.0 * pBB->getDimensions().getHeight();

  QGraphicsRectItem* result = new QRoundedRect(
    x, y, w, h, rx, ry);
  QPen *pen = getPen(pRect, group, resolver, pBB);
  result->setPen(*pen);
  delete pen;
  QBrush *brush = getBrush(pRect, group, resolver, pBB);
  result->setBrush(*brush);
  delete brush;
  transform(result, pRect, group);
  item->addToGroup(result);
}
void TutorialDlg::createSceneAndView ()
{
  LOG4CPP_INFO_S ((*mainCat)) << "TutorialDlg::createSceneAndView";

  m_scene = new QGraphicsScene (this);

  m_view = new QGraphicsView (m_scene, this);
  m_view->setMouseTracking (true);
  layout ()->addWidget(m_view);

  // Spacer is used to ensure view is the desired size. Directly setting the size of the view
  // is ineffective since the view then get resized to the smallest rectangle fitting the added items
  QGraphicsRectItem *spacer = new QGraphicsRectItem (0,
                                                     0,
                                                     backgroundSize().width (),
                                                     backgroundSize().height ());
  spacer->setBrush (QBrush (Qt::NoBrush));
  spacer->setPen (QPen (Qt::NoPen));
  spacer->setZValue(-1); // Put behind everything else at the default z of zero
  m_scene->addItem (spacer);
}
void PSV_CircularIndicatorItem::drawOuterCircle(int zValue)
{
    QRadialGradient outerGradient(m_rect.center(), m_outerRadius, m_rect.center());
    outerGradient.setColorAt(0.0, QColor(200, 200, 200));
    outerGradient.setColorAt(0.9, QColor(80, 80, 80));
    outerGradient.setColorAt(0.95, QColor(180, 180, 180));
    outerGradient.setColorAt(1.0, QColor(80, 80, 80));
    //==========================
    QPen pen(Qt::NoPen);
    QGraphicsEllipseItem* item = new QGraphicsEllipseItem(this);
    item->setRect(m_rect.center().x() - m_outerRadius, m_rect.center().y() - m_outerRadius, m_outerRadius*2, m_outerRadius*2);
    item->setPen(pen);
    item->setBrush(outerGradient);
    item->setZValue(zValue);
    {//TEST

        QGraphicsRectItem *item = new QGraphicsRectItem(m_rect, this);
        item->setPen(QPen(Qt::blue));
        //        item->setPen();
    }
}
Exemple #26
0
void tst_QGraphicsEffect::dropShadowClipping()
{
    QImage img(128, 128, QImage::Format_ARGB32_Premultiplied);
    img.fill(0xffffffff);

    QGraphicsScene scene;
    QGraphicsRectItem *item = new QGraphicsRectItem(-5, -500, 10, 1000);
    item->setGraphicsEffect(new QGraphicsDropShadowEffect);
    item->setPen(Qt::NoPen);
    item->setBrush(Qt::red);

    scene.addItem(item);

    QPainter p(&img);
    scene.render(&p, img.rect(), QRect(-64, -64, 128, 128));
    p.end();

    for (int y = 1; y < img.height(); ++y)
        for (int x = 0; x < img.width(); ++x)
            QCOMPARE(img.pixel(x, y), img.pixel(x, y-1));
}
Exemple #27
0
void TankItem::createBar(qreal x, qreal w, struct gasmix *gas)
{
	// pick the right gradient, size, position and text
	QGraphicsRectItem *rect = new QGraphicsRectItem(x, 0, w, height, this);
	if (gasmix_is_air(gas))
		rect->setBrush(air);
	else if (gas->he.permille)
		rect->setBrush(trimix);
	else if (gas->o2.permille == 1000)
		rect->setBrush(oxygen);
	else
		rect->setBrush(nitrox);
	rect->setPen(QPen(QBrush(), 0.0)); // get rid of the thick line around the rectangle
	rects.push_back(rect);
	DiveTextItem *label = new DiveTextItem(rect);
	label->setText(gasname(gas));
	label->setBrush(Qt::black);
	label->setPos(x + 1, 0);
	label->setAlignment(Qt::AlignBottom | Qt::AlignRight);
	label->setZValue(101);
}
void Canvas::setSceneRect(qreal x, qreal y, qreal w, qreal h)
{
    currentScene->setSceneRect(x, y, w, h);

    qreal borderWidth = 0.5;
    QPen borderPen(QBrush(Qt::black), borderWidth);
    borderPen.setCapStyle(Qt::SquareCap);
    borderPen.setJoinStyle(Qt::MiterJoin);

    qreal shadowWidth = 5;
    QPen shadowPen(QBrush(Qt::lightGray), shadowWidth);
    shadowPen.setCapStyle(Qt::SquareCap);
    shadowPen.setJoinStyle(Qt::MiterJoin);

    QGraphicsItemGroup * group = new QGraphicsItemGroup;

    QGraphicsLineItem * shadowRight =
            new QGraphicsLineItem(x + w + (shadowWidth - borderWidth) / 2,
                                  y + shadowWidth,
                                  x + w + (shadowWidth - borderWidth) / 2,
                                  y + h + shadowWidth / 2);
    shadowRight->setPen(shadowPen);

    QGraphicsLineItem * shadowBottom =
            new QGraphicsLineItem(x + shadowWidth,
                                  y + h + (shadowWidth - borderWidth) / 2,
                                  x + w + shadowWidth / 2,
                                  y + h + (shadowWidth - borderWidth) / 2);
    shadowBottom->setPen(shadowPen);

    QGraphicsRectItem * rect = new QGraphicsRectItem(x, y, w, h);
    rect->setPen(borderPen);

    group->addToGroup(shadowRight);
    group->addToGroup(shadowBottom);
    group->addToGroup(rect);

    currentScene->addItem(group);
}
int main(int argc, char * argv[])
{
	if(argc<3)
	{
		showUsage();
	}
	QTime time;

	// GUI stuff
	QApplication app(argc, argv);

	time.start();
	//Load as grayscale
	cv::Mat objectImg = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
	cv::Mat sceneImg = cv::imread(argv[2], cv::IMREAD_GRAYSCALE);

	if(!objectImg.empty() && !sceneImg.empty())
	{
		printf("Loading images: %d ms\n", time.restart());
		std::vector<cv::KeyPoint> objectKeypoints;
		std::vector<cv::KeyPoint> sceneKeypoints;
		cv::Mat objectDescriptors;
		cv::Mat sceneDescriptors;

		////////////////////////////
		// EXTRACT KEYPOINTS
		////////////////////////////
		cv::Ptr<cv::FeatureDetector> detector;
		// The detector can be any of (see OpenCV features2d.hpp):
#if CV_MAJOR_VERSION == 2
		// detector = cv::Ptr(new cv::DenseFeatureDetector());
		// detector = cv::Ptr(new cv::FastFeatureDetector());
		// detector = cv::Ptr(new cv::GFTTDetector());
		// detector = cv::Ptr(new cv::MSER());
		// detector = cv::Ptr(new cv::ORB());
		detector = cv::Ptr<cv::FeatureDetector>(new cv::SIFT());
		// detector = cv::Ptr(new cv::StarFeatureDetector());
		// detector = cv::Ptr(new cv::SURF(600.0));
		// detector = cv::Ptr(new cv::BRISK());
#else
		detector = cv::xfeatures2d::SIFT::create();
#endif
		detector->detect(objectImg, objectKeypoints);
		printf("Object: %d keypoints detected in %d ms\n", (int)objectKeypoints.size(), time.restart());
		detector->detect(sceneImg, sceneKeypoints);
		printf("Scene: %d keypoints detected in %d ms\n", (int)sceneKeypoints.size(), time.restart());

		////////////////////////////
		// EXTRACT DESCRIPTORS
		////////////////////////////
		cv::Ptr<cv::DescriptorExtractor> extractor;
#if CV_MAJOR_VERSION == 2
		// The extractor can be any of (see OpenCV features2d.hpp):
		// extractor = cv::Ptr(new cv::BriefDescriptorExtractor());
		// extractor = cv::Ptr(new cv::ORB());
		extractor = cv::Ptr<cv::DescriptorExtractor>(new cv::SIFT());
		// extractor = cv::Ptr(new cv::SURF(600.0));
		// extractor = cv::Ptr(new cv::BRISK());
		// extractor = cv::Ptr(new cv::FREAK());
#else
		extractor = cv::xfeatures2d::SIFT::create();
#endif
		extractor->compute(objectImg, objectKeypoints, objectDescriptors);
		printf("Object: %d descriptors extracted in %d ms\n", objectDescriptors.rows, time.restart());
		extractor->compute(sceneImg, sceneKeypoints, sceneDescriptors);
		printf("Scene: %d descriptors extracted in %d ms\n", sceneDescriptors.rows, time.restart());

		////////////////////////////
		// NEAREST NEIGHBOR MATCHING USING FLANN LIBRARY (included in OpenCV)
		////////////////////////////
		cv::Mat results;
		cv::Mat dists;
		std::vector<std::vector<cv::DMatch> > matches;
		int k=2; // find the 2 nearest neighbors
		bool useBFMatcher = false; // SET TO TRUE TO USE BRUTE FORCE MATCHER
		if(objectDescriptors.type()==CV_8U)
		{
			// Binary descriptors detected (from ORB, Brief, BRISK, FREAK)
			printf("Binary descriptors detected...\n");
			if(useBFMatcher)
			{
				cv::BFMatcher matcher(cv::NORM_HAMMING); // use cv::NORM_HAMMING2 for ORB descriptor with WTA_K == 3 or 4 (see ORB constructor)
				matcher.knnMatch(objectDescriptors, sceneDescriptors, matches, k);
			}
			else
			{
				// Create Flann LSH index
				cv::flann::Index flannIndex(sceneDescriptors, cv::flann::LshIndexParams(12, 20, 2), cvflann::FLANN_DIST_HAMMING);
				printf("Time creating FLANN LSH index = %d ms\n", time.restart());

				// search (nearest neighbor)
				flannIndex.knnSearch(objectDescriptors, results, dists, k, cv::flann::SearchParams() );
			}
		}
		else
		{
			// assume it is CV_32F
			printf("Float descriptors detected...\n");
			if(useBFMatcher)
			{
				cv::BFMatcher matcher(cv::NORM_L2);
				matcher.knnMatch(objectDescriptors, sceneDescriptors, matches, k);
			}
			else
			{
				// Create Flann KDTree index
				cv::flann::Index flannIndex(sceneDescriptors, cv::flann::KDTreeIndexParams(), cvflann::FLANN_DIST_EUCLIDEAN);
				printf("Time creating FLANN KDTree index = %d ms\n", time.restart());

				// search (nearest neighbor)
				flannIndex.knnSearch(objectDescriptors, results, dists, k, cv::flann::SearchParams() );
			}
		}
		printf("Time nearest neighbor search = %d ms\n", time.restart());

		// Conversion to CV_32F if needed
		if(dists.type() == CV_32S)
		{
			cv::Mat temp;
			dists.convertTo(temp, CV_32F);
			dists = temp;
		}


		////////////////////////////
		// PROCESS NEAREST NEIGHBOR RESULTS
		////////////////////////////
		// Set gui data
		ObjWidget objWidget(0, objectKeypoints, QMultiMap<int,int>(), cvtCvMat2QImage(objectImg));
		ObjWidget sceneWidget(0, sceneKeypoints, QMultiMap<int,int>(), cvtCvMat2QImage(sceneImg));

		// Find correspondences by NNDR (Nearest Neighbor Distance Ratio)
		float nndrRatio = 0.8f;
		std::vector<cv::Point2f> mpts_1, mpts_2; // Used for homography
		std::vector<int> indexes_1, indexes_2; // Used for homography
		std::vector<uchar> outlier_mask;  // Used for homography
		// Check if this descriptor matches with those of the objects
		if(!useBFMatcher)
		{
			for(int i=0; i<objectDescriptors.rows; ++i)
			{
				// Apply NNDR
				//printf("q=%d dist1=%f dist2=%f\n", i, dists.at<float>(i,0), dists.at<float>(i,1));
				if(results.at<int>(i,0) >= 0 && results.at<int>(i,1) >= 0 &&
				   dists.at<float>(i,0) <= nndrRatio * dists.at<float>(i,1))
				{
					mpts_1.push_back(objectKeypoints.at(i).pt);
					indexes_1.push_back(i);

					mpts_2.push_back(sceneKeypoints.at(results.at<int>(i,0)).pt);
					indexes_2.push_back(results.at<int>(i,0));
				}
			}
		}
		else
		{
			for(unsigned int i=0; i<matches.size(); ++i)
			{
				// Apply NNDR
				//printf("q=%d dist1=%f dist2=%f\n", matches.at(i).at(0).queryIdx, matches.at(i).at(0).distance, matches.at(i).at(1).distance);
				if(matches.at(i).size() == 2 &&
				   matches.at(i).at(0).distance <= nndrRatio * matches.at(i).at(1).distance)
				{
					mpts_1.push_back(objectKeypoints.at(matches.at(i).at(0).queryIdx).pt);
					indexes_1.push_back(matches.at(i).at(0).queryIdx);

					mpts_2.push_back(sceneKeypoints.at(matches.at(i).at(0).trainIdx).pt);
					indexes_2.push_back(matches.at(i).at(0).trainIdx);
				}
			}
		}

		// FIND HOMOGRAPHY
		unsigned int minInliers = 8;
		if(mpts_1.size() >= minInliers)
		{
			time.start();
			cv::Mat H = findHomography(mpts_1,
					mpts_2,
					cv::RANSAC,
					1.0,
					outlier_mask);
			printf("Time finding homography = %d ms\n", time.restart());
			int inliers=0, outliers=0;
			for(unsigned int k=0; k<mpts_1.size();++k)
			{
				if(outlier_mask.at(k))
				{
					++inliers;
				}
				else
				{
					++outliers;
				}
			}
			QTransform hTransform(
			H.at<double>(0,0), H.at<double>(1,0), H.at<double>(2,0),
			H.at<double>(0,1), H.at<double>(1,1), H.at<double>(2,1),
			H.at<double>(0,2), H.at<double>(1,2), H.at<double>(2,2));

			// GUI : Change color and add homography rectangle
			QColor color(Qt::green);
			int alpha = 130;
			color.setAlpha(alpha);
			for(unsigned int k=0; k<mpts_1.size();++k)
			{
				if(outlier_mask.at(k))
				{
					objWidget.setKptColor(indexes_1.at(k), color);
					sceneWidget.setKptColor(indexes_2.at(k), color);
				}
				else
				{
					objWidget.setKptColor(indexes_1.at(k), QColor(255,0,0,alpha));
					sceneWidget.setKptColor(indexes_2.at(k), QColor(255,0,0,alpha));
				}
			}
			QPen rectPen(color);
			rectPen.setWidth(4);
			QGraphicsRectItem * rectItem = new QGraphicsRectItem(objWidget.pixmap().rect());
			rectItem->setPen(rectPen);
			rectItem->setTransform(hTransform);
			sceneWidget.addRect(rectItem);
			printf("Inliers=%d Outliers=%d\n", inliers, outliers);
		}
		else
		{
			printf("Not enough matches (%d) for homography...\n", (int)mpts_1.size());
		}

		// Wait for gui
		objWidget.setGraphicsViewMode(false);
		objWidget.setWindowTitle("Object");
		if(objWidget.pixmap().width() <= 800)
		{
			objWidget.setMinimumSize(objWidget.pixmap().width(), objWidget.pixmap().height());
		}
		else
		{
			objWidget.setMinimumSize(800, 600);
			objWidget.setAutoScale(false);
		}

		sceneWidget.setGraphicsViewMode(false);
		sceneWidget.setWindowTitle("Scene");
		if(sceneWidget.pixmap().width() <= 800)
		{
			sceneWidget.setMinimumSize(sceneWidget.pixmap().width(), sceneWidget.pixmap().height());
		}
		else
		{
			sceneWidget.setMinimumSize(800, 600);
			sceneWidget.setAutoScale(false);
		}

		sceneWidget.show();
		objWidget.show();

		int r = app.exec();
		printf("Closing...\n");

		return r;
	}
	else
	{
		printf("Images are not valid!\n");
		showUsage();
	}

	return 1;
}
Exemple #30
0
bool ZipplXmlReader::read( QIODevice *dev )
{
  setDevice( dev );
  bool res = true;
  bool metaMode = false;
  mCurrParent = 0;
  mCurrSpot = 0;

  QGraphicsScene *scene = mGraphWidget->scene();
  int spotID = 0;

  while (!atEnd()) {
    readNext();

    if( isStartElement() ) {
      qDebug() << "XML name: " << name();

      if( name() == "presentation") {
        // presentation mode: debug & presentation
        QString mode = attributes().value("mode").toString();
        if( !mode.isEmpty() ) mMode = mode;

        mPath = attributes().value("path").toString();
        if( !mPath.endsWith('/') ) mPath += "/";


        qreal dx = qrealAttrib("width") / -2.0;
        qreal dy = qrealAttrib("height") / -2.0;
        QRectF rect( dx, dy, -2.0*dx, -2.0*dy );
        scene->setSceneRect( rect );
      } else if( name() == "meta" ) {
        metaMode = true;
      } else if( name() == "title" && metaMode ) {
        mPresentationTitle = readElementText();
      } else if( name() == "description" && metaMode ) {
        mPresentationDescr = readElementText();
      } else if( name() == "date" && metaMode ) {
        mPresentationDate = readElementText();
      } else if( name() == "name" && metaMode ) {
        mAuthorName = readElementText();
      } else if( name() == "email" && metaMode ) {
        mAuthorEmail = readElementText();
      } else if( name() == "tocentry" ) {
        if( mCurrSpot ) {
          mCurrSpot->setData( TOCENTRY, readElementText() );
        }
      } else if( name() == "spot" ) {
        if( mCurrParent != 0 ) {
          qDebug() << "Strange: Current Parent should be zero here!";
        }
        QGraphicsRectItem *rectItem = new QGraphicsRectItem( );

        rectItem->setPen( pen( rectItem->pen(), QColor("#aeaeae") ));

        mCurrParent = rectItem;
        mCurrSpot = rectItem;
        mCurrParent->setData( ID, QVariant( spotID++ ));

        mCurrParent->setPos( position() );

        rectItem->setBrush( brush( rectItem->brush() ) );

        scene->addItem( mCurrParent );
        mSpots.append( mCurrParent );

        // Prepare the hidden items list
        GraphicsItemList list;
        mHiddenItems.insert( mCurrParent, list );

      } else if( name() == "hidden" ) {
        QGraphicsRectItem *rectItem = new QGraphicsRectItem( mCurrParent, scene );
        rectItem->setPen( QPen( QColor( 240, 240, 240 )));

        // append this hidden item to the list of hiddens of the parent spot.
        GraphicsItemList list = mHiddenItems[mCurrSpot];
        list.append( rectItem );
        mHiddenItems[mCurrSpot] = list;

        mCurrParent = rectItem;
        mCurrParent->setData( ID, QVariant( spotID++ ));

      } else if( name() == "rect" ) {
        if( mCurrParent ) { // within a spot
          qDebug() << "Creating a rectangle!";
          QGraphicsRectItem *rectItem = new QGraphicsRectItem( mCurrParent, scene );

          qreal width = qrealAttrib( "width" );
          qreal height = qrealAttrib( "height" );

          QPointF pos = position();
          if( width > 0 && height > 0 ) {
            rectItem->setRect( pos.x(), pos.y(), width, height );
          } else {
            rectItem->setPos( pos );
          }
          rectItem->setPen( pen( rectItem->pen() ) );

          mCurrParent = rectItem;
        }
      } else if( name() == "circle" ) {
        QPointF pos = position();
        QGraphicsEllipseItem *ellipse = new QGraphicsEllipseItem( mCurrParent, scene );
        // ellipse->setBrush( getBrush() );
        qreal r = 2.0 * qrealAttrib( "r" );

        QRectF rect( pos, QSizeF( r, r ) );

        ellipse->setPen( pen( ellipse->pen() ) );

        ellipse->setRect( rect );


      } else if( name() == "text" ) {
        QGraphicsSimpleTextItem *textItem = new QGraphicsSimpleTextItem( mCurrParent, scene );

        QString font = attributes().value("font").toString();
        QString size = attributes().value("size").toString();


        QFont currFont = textItem->font();
        if( !font.isEmpty() ) {
          currFont.setFamily( font );
          textItem->setFont( currFont );
        }
        if( !size.isEmpty() ) {
          currFont.setPointSize( size.toInt() );
          textItem->setFont( currFont );
        }

        textItem->setPos( position() );

        // set the brush
        QBrush b( textItem->brush() );
        b.setColor( color() );

        textItem->setBrush( b );

        QString text = readElementText();
        textItem->setText( text );

      } else if( name() == "image" ) {
        if( handleImg( scene ) ) {

        }
      }
    } else if( isEndElement() ) {
      qDebug( ) << "XML CLOSE: " << name().toString();
      if( name() == "spot" || name() == "toc" ) {
        QRectF rect = mCurrParent->childrenBoundingRect();
        rect.setX(0);
        rect.setY(0);
        qgraphicsitem_cast<QGraphicsRectItem*>(mCurrParent)->setRect( rect);
        mCurrParent = 0;
      } else if( name() == "rect" ) {
        QGraphicsRectItem *item = qgraphicsitem_cast<QGraphicsRectItem*>(mCurrParent);

        if( item->rect().isEmpty() )
          item->setRect( mCurrParent->childrenBoundingRect() );
        mCurrParent = mCurrParent->parentItem();
      } else if( name() == "hidden") {
        mCurrParent->setOpacity( 0.0 );
        mCurrParent = mCurrParent->parentItem();
      } else if( name() == "meta" ) {
        metaMode = false;
      }
    }
  }

  createToc( scene );

  return res;
}