Exemplo n.º 1
0
void tst_QGraphicsEffect::boundingRect2()
{
    CustomEffect *effect = new CustomEffect;
    QGraphicsRectItem *root = new QGraphicsRectItem;
    root->setGraphicsEffect(effect);

    QGraphicsRectItem *child = new QGraphicsRectItem;
    QRectF childRect(0, 0, 100, 100);
    child->setFlag(QGraphicsItem::ItemClipsChildrenToShape);
    child->setRect(childRect);
    child->setParentItem(root);

    QGraphicsRectItem *grandChild = new QGraphicsRectItem;
    QRectF grandChildRect(0, 0, 200, 200);
    grandChild->setRect(grandChildRect);
    grandChild->setParentItem(child);

    // Make sure the effect's bounding rect is clipped to the child's bounding rect.
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(childRect));

    // Disable ItemClipsChildrenToShape; effect's bounding rect is no longer clipped.
    child->setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(childRect | grandChildRect));

    // Add root item to a scene, do the same tests as above. Results should be the same.
    QGraphicsScene scene;
    scene.addItem(root);

    child->setFlag(QGraphicsItem::ItemClipsChildrenToShape);
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(childRect));

    child->setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(childRect | grandChildRect));

    // Now add the scene to a view, results should be the same.
    QGraphicsView view(&scene);

    child->setFlag(QGraphicsItem::ItemClipsChildrenToShape);
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(childRect));

    child->setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(childRect | grandChildRect));

    CustomEffect *childEffect = new CustomEffect;
    child->setGraphicsEffect(childEffect);
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(childEffect->boundingRectFor(childRect | grandChildRect)));

    child->setGraphicsEffect(0);
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(childRect | grandChildRect));
}
Exemplo n.º 2
0
void tst_QGraphicsEffect::boundingRect()
{
    // No source; empty bounding rect.
    CustomEffect *effect = new CustomEffect;
    QCOMPARE(effect->boundingRect(), QRectF());

    // Install effect on QGraphicsItem.
    QRectF itemRect(0, 0, 100, 100);
    QGraphicsRectItem *item = new QGraphicsRectItem;
    item->setRect(itemRect);
    item->setGraphicsEffect(effect);
    int margin = effect->margin();
    QCOMPARE(effect->boundingRect(), itemRect.adjusted(-margin, -margin, margin, margin));
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(itemRect));

    // Make sure disabling/enabling the effect doesn't change the bounding rect.
    effect->setEnabled(false);
    QCOMPARE(effect->boundingRect(), itemRect.adjusted(-margin, -margin, margin, margin));
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(itemRect));
    effect->setEnabled(true);
    QCOMPARE(effect->boundingRect(), itemRect.adjusted(-margin, -margin, margin, margin));
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(itemRect));

    // Change effect margins.
    effect->setMargin(margin = 20);
    QCOMPARE(effect->boundingRect(), itemRect.adjusted(-margin, -margin, margin, margin));
    QCOMPARE(effect->boundingRect(), effect->boundingRectFor(itemRect));

    // Uninstall effect on QGraphicsItem.
    QPointer<CustomEffect> ptr = effect;
    item->setGraphicsEffect(0);
    QVERIFY(!ptr);

    delete item;
}
Exemplo n.º 3
0
QGraphicsItem* CGraphicsRectItem::createItem()
{
	QGraphicsRectItem* pItem = new QGraphicsRectItem(m_Parent);

	drawPen(pItem);
	drawBrush(pItem);

	pItem->setRect(GET_VALUE(x).toInt(),GET_VALUE(y).toInt(),GET_VALUE(w).toInt(),GET_VALUE(h).toInt());
	return pItem;
}
Exemplo n.º 4
0
    virtual void operator()(QGraphicsItem* item, const QRectF& rect)
    {
        QGraphicsRectItem* rectItem =
                dynamic_cast<QGraphicsRectItem*>(item);

        if (rectItem)
        {
            rectItem->setRect(rect);
        }
    }
Exemplo n.º 5
0
PacMan::PacMan(int width, int height, QColor color, int layer , double startX, double startY, double endX, double endY, int startSec, int endSec)
 : width(width) , height(height) , color(color) , layer(layer) , startX(startX) , startY(startY) , endX(endX) , endY(endY) , startSec(startSec) , endSec(endSec)
{
    moveScale= 1;

    QGraphicsRectItem * rect = new QGraphicsRectItem(this);

    rect->setRect ( -width/2 , -height/2 , width , height );
    rect->setBrush (QBrush(color));
    liveSec = endSec - startSec;

    setZValue(layer);
}
Exemplo n.º 6
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);
}
Exemplo n.º 7
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);	
}
Exemplo n.º 8
0
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;
}
Exemplo n.º 9
0
QGraphicsRectItem *Board::CreateBoard()
{
    QGraphicsRectItem *item = new QGraphicsRectItem;
    QPixmap *pixmap = new QPixmap("D:\\programmieren\\RealChess\\ChessBoard.PNG");
    QBrush *brush = new QBrush();

    if(pixmap->isNull()) {
        item->setBrush(Qt::green);
    }
    else {
        brush->setTexture(*pixmap);
        item->setBrush(*pixmap);
    }
    item->setRect(0,0,600,600);


    return item;

}
Exemplo n.º 10
0
void SymbolDataEditor::moveItem(const QPoint pos)
{
    if (itemToChange == Item::NoItem || scene->items().isEmpty())
        return;

    if (itemToChange == Item::InPoint || itemToChange == Item::OutPoint)
    {
        QPointF itemPos = mapToScene(pos);
        QGraphicsEllipseItem* item = static_cast<QGraphicsEllipseItem *>(scene->items(Qt::AscendingOrder).at(itemToChange));
        item->setRect(itemPos.x() - pointWidth / 2,
                      itemPos.y() - pointWidth / 2,
                      pointWidth, pointWidth);
    }

    if (itemToChange == Item::LimitsRect)
    {
        QGraphicsRectItem* item = static_cast<QGraphicsRectItem *>(scene->items(Qt::AscendingOrder).at(itemToChange));

        QPointF scenePos = mapToScene(pos);
        QRectF newRect = item->rect();

        if (sideToChange & Side::Top)
            newRect.setTop(scenePos.y());
        if (sideToChange & Side::Bottom)
            newRect.setBottom(scenePos.y());
        if (sideToChange & Side::Left)
            newRect.setLeft(scenePos.x());
        if (sideToChange & Side::Right)
            newRect.setRight(scenePos.x());

        if (sideToChange == Side::AllSides)
        {
            newRect.moveCenter(scenePos + dLimitsCenter);
        }

        item->setRect(newRect);
    }
}
Exemplo n.º 11
0
void SymbolDataEditor::correctLimits()
{
    if (limits.height() < 0)
    {
        qreal top = limits.top();
        limits.setTop(limits.bottom());
        limits.setBottom(top);
    }

    if (limits.width() < 0)
    {
        qreal left = limits.left();
        limits.setLeft(limits.right());
        limits.setRight(left);
    }

    if (scene->items().size() > Item::LimitsRect)
    {
        QGraphicsRectItem* limitsRectItem = static_cast<QGraphicsRectItem *>(scene->items(Qt::AscendingOrder).at(Item::LimitsRect));
        limitsRectItem->setRect(limits);
    }

}
Exemplo n.º 12
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;
}
Exemplo n.º 13
0
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QGraphicsScene* scene= new QGraphicsScene(QRectF(0,0,_WINDOW_SIZE_X,_WINDOW_SIZE_Y));
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    QGraphicsView view(scene);

    view.setWindowTitle("Battle manager");
    view.setRenderHint(QPainter::Antialiasing);
    view.setCacheMode(QGraphicsView::CacheBackground);
    view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);

    QGraphicsRectItem* pRectItem = new QGraphicsRectItem(0, scene);
    pRectItem->setPen(QPen(Qt::black));
    pRectItem->setBrush(QBrush(Qt::green));
    pRectItem->setRect(QRectF(0,0,_WINDOW_SIZE_X,_WINDOW_SIZE_Y));

    QGraphicsRectItem* pRectItem2 = new QGraphicsRectItem(0, scene);
    pRectItem2->setPen(QPen(Qt::black));
    pRectItem2->setBrush(QBrush(Qt::cyan));
    pRectItem2->setRect(QRectF(20,20,_WINDOW_SIZE_X-40,_WINDOW_SIZE_Y-40));

    TickLabel = new QLabel("0000000000");
    TickLabel->setAlignment(Qt::AlignHCenter);
    TickLabel->move(_WINDOW_SIZE_X/2-45,3);
    TickLabel->setStyleSheet("background-color: yellow");
    scene->addWidget(TickLabel);

    Score1Label = new QLabel("000000000000");
    Score1Label->setAlignment(Qt::AlignCenter);
    Score1Label->move(50,3);
    Score1Label->setStyleSheet("background-color: yellow");
    scene->addWidget(Score1Label);

    Score2Label = new QLabel("000000000000");
    Score2Label->setAlignment(Qt::AlignCenter);
    Score2Label->move(_WINDOW_SIZE_X-120,3);
    Score2Label->setStyleSheet("background-color: yellow");
    scene->addWidget(Score2Label);
    view.show();

    ar->SetScene(scene);
    ar->Prepare();
    MyTimer* Timer1 = new MyTimer;
    counter = 0;

    ar->SetMemberOne(m1);
    ar->SetMemberTwo(m2);

    //------раскомментировать для создания базы (первый запуск)-------
    //pDB->AddPlayer(1, "Test");
    //pDB->CreateTable(1);
    //----------------------------------------------------------------

    //----раскомментировать для генерации новой популяции в памяти----
    //srand(time(0));
    //p->Generate();
    //----------------------------------------------------------------

    //----раскомментировать для загрузки начальной популяции из базы--
    p->Load();
    //----------------------------------------------------------------

    if (_FAST_CALC==1) //настраивается выше в разделе объявлений
    {
        for (int j = 1;j<=50;j++)//количество популяций
        {
            counter = 0;
            Population* pNew = p->Evolve(1,0);
            pNew->CopyTo(p);
            delete pNew;

            for (unsigned int i=0;i<_POPULATION_SIZE;i++)
            {
                ar->Initialization(Timer1);
                ar->Simulate();
            }
            p->Sort();
            cout<<"Leader fitness after "<<j<<" = "<<p->members[0]->GetFitness()<<endl;
        }
        p->Save(); //сохраняется только самая последняя популяция
    }
    else
    {
        Population* pNew = p->Evolve(1,0);
        pNew->CopyTo(p);
        delete pNew;
        ar->Initialization(Timer1);
    }

    return app.exec();
}
Exemplo n.º 14
0
void
MatrixElement::reconfigure(timeT time, timeT duration, int pitch, int velocity)
{
    const RulerScale *scale = m_scene->getRulerScale();
    int resolution = m_scene->getYResolution();

    double x0 = scale->getXForTime(time);
    double x1 = scale->getXForTime(time + duration);
    m_width = x1 - x0;

    m_velocity = velocity;

    // if the note has TIED_FORWARD or TIED_BACK properties, draw it with a
    // different fill pattern
    bool tiedNote = (event()->has(BaseProperties::TIED_FORWARD) ||
                     event()->has(BaseProperties::TIED_BACKWARD));
    Qt::BrushStyle brushPattern = (tiedNote ? Qt::Dense2Pattern : Qt::SolidPattern);

    QColor colour;
    if (event()->has(BaseProperties::TRIGGER_SEGMENT_ID)) {
        //!!! Using gray for trigger events and events from other, non-active
        // segments won't work.  This should be handled some other way, with a
        // color outside the range of possible velocity choices, which probably
        // leaves some kind of curious light blue or something
        colour = Qt::cyan;
    } else {
        colour = DefaultVelocityColour::getInstance()->getColour(velocity);
    }
    colour.setAlpha(160);

    double fres(resolution);

    if (m_drum) {
        fres = resolution + 1;
        QGraphicsPolygonItem *item = dynamic_cast<QGraphicsPolygonItem *>(m_item);
        if (!item) {
            delete m_item;
            item = new QGraphicsPolygonItem;
            m_item = item;
            m_scene->addItem(m_item);
        }
        QPolygonF polygon;
        polygon << QPointF(0, 0)
                << QPointF(fres/2, fres/2)
                << QPointF(0, fres)
                << QPointF(-fres/2, fres/2)
                << QPointF(0, 0);
        item->setPolygon(polygon);
        item->setPen
            (QPen(GUIPalette::getColour(GUIPalette::MatrixElementBorder), 0));
        item->setBrush(QBrush(colour, brushPattern));
    } else {
        QGraphicsRectItem *item = dynamic_cast<QGraphicsRectItem *>(m_item);
        if (!item) {
            delete m_item;
            item = new QGraphicsRectItem;
            m_item = item;
            m_scene->addItem(m_item);
        }
        float width = m_width;
        if (width < 1) width = 1;
        QRectF rect(0, 0, width, fres + 1);
        item->setRect(rect);
        item->setPen
            (QPen(GUIPalette::getColour(GUIPalette::MatrixElementBorder), 0));
        item->setBrush(QBrush(colour, brushPattern));
    }

    setLayoutX(x0);

    m_item->setData(MatrixElementData, QVariant::fromValue((void *)this));

    // set the Y position taking m_pitchOffset into account, subtracting the
    // opposite of whatever the originating segment transpose was

//    std::cout << "TRANSPOSITION TEST: event pitch: "
//              << (pitch ) << " m_pitchOffset: " << m_pitchOffset
//              << std::endl;

    m_item->setPos(x0, (127 - pitch - m_pitchOffset) * (resolution + 1));

    // set a tooltip explaining why this event is drawn in a different pattern
    if (tiedNote) m_item->setToolTip(QObject::tr("This event is tied to another event."));
}
Exemplo n.º 15
0
void BaseDrawingWidget::handleDrawingState(DrawingState state, QPointF lastPoint)
{
    // handle drawing start/update/end events for the current drawing mode

    QPainter::CompositionMode prevCompMode;

    if(state == DRAWINGSTATE_START) {
        // start a new series of paint operations on the picture
        picturePainter.begin(&picture);
        // set the drawing style for the painter
        picturePainter.setPen(drawingPen);
        picturePainter.setBrush(drawingBrush);
    }

    switch(drawingMode) {
        case DRAWINGMODE_FREEHAND:
            if(state == DRAWINGSTATE_START) {
                QGraphicsLineItem * newLine = new QGraphicsLineItem(QLineF(lastPoint, lastPoint), 0, getDrawingData());
                currentItem = newLine;
                newLine->setPen(drawingPen);
            }

            else if(state == DRAWINGSTATE_UPDATE) {
                QGraphicsLineItem * newLine = new QGraphicsLineItem(currentItem, getDrawingData());
                newLine->setLine(QLineF(mousePrevPoint, lastPoint));
                newLine->setPen(drawingPen);
                picturePainter.drawLine(mousePrevPoint, lastPoint);
            }

            else {
                QGraphicsLineItem * newLine = new QGraphicsLineItem(currentItem, getDrawingData());
                newLine->setLine(QLineF(mousePrevPoint, lastPoint));
                newLine->setPen(drawingPen);
                // remove the temporary QGraphicsItem
                getDrawingData()->removeItem(currentItem);
                picturePainter.drawLine(mousePrevPoint, lastPoint);
             }

            break;

        case DRAWINGMODE_RECTANGLE:
            if(state == DRAWINGSTATE_START) {
                // create a temporary QGraphicsItem
                // will be committed to the drawing when the mouse is released
                QGraphicsRectItem * newRect = new QGraphicsRectItem(lastPoint.x(), lastPoint.y(),0,0);
                currentItem = (QGraphicsItem *) newRect;
                newRect->setPen(drawingPen);
                newRect->setBrush(drawingBrush);
                drawingData->addItem(currentItem);
            }

            else if(state == DRAWINGSTATE_UPDATE)
                // update the temporary QGraphicsItem
                ((QGraphicsRectItem*)currentItem)->setRect(QRectF(mouseDownPoint,lastPoint).normalized());

            else {
                // remove the temporary QGraphicsItem
                getDrawingData()->removeItem(currentItem);
                // commit the drawing to the stage pixmap
                picturePainter.drawRect(QRectF(mouseDownPoint,lastPoint).normalized());
            }
            break;

        case DRAWINGMODE_STRAIGHTLINE:
            if(state == DRAWINGSTATE_START) {
                // create a temporary QGraphicsItem
                // will be committed to the drawing when the mouse is released
                QGraphicsLineItem * newLine = new QGraphicsLineItem(QLineF(lastPoint, lastPoint));
                currentItem = (QGraphicsItem*) newLine;
                newLine->setPen(drawingPen);
                getDrawingData()->addItem(newLine);
            }

            else if(state == DRAWINGSTATE_UPDATE) {
                // update the temporary QGraphicsItem
                ((QGraphicsLineItem*)currentItem)->setLine(QLineF(mouseDownPoint, lastPoint));
            }

            else {
                // remove the temporary QGraphicsItem
                getDrawingData()->removeItem(currentItem);
                // commit the drawing to the stage pixmap
                picturePainter.drawLine(QLineF(mouseDownPoint, lastPoint));
            }
            break;

        case DRAWINGMODE_ELLIPSE:
            if(state == DRAWINGSTATE_START) {
                // create a temporary QGraphicsItem
                // will be committed to the drawing when the mouse is released
                QGraphicsEllipseItem * newRect = new QGraphicsEllipseItem(lastPoint.x(), lastPoint.y(),0,0);
                currentItem = (QGraphicsItem *) newRect;
                newRect->setPen(drawingPen);
                newRect->setBrush(drawingBrush);
                drawingData->addItem(currentItem);
            }

            else if(state == DRAWINGSTATE_UPDATE)
                // update the temporary QGraphicsItem
                ((QGraphicsRectItem*)currentItem)->setRect(QRectF(mouseDownPoint,lastPoint).normalized());

            else {
                // remove the temporary QGraphicsItem
                getDrawingData()->removeItem(currentItem);
                // commit the drawing to the stage pixmap
                picturePainter.drawEllipse(QRectF(mouseDownPoint,lastPoint).normalized());
            }
            break;

        case DRAWINGMODE_ERASER:
            if(state == DRAWINGSTATE_START) {
                QGraphicsRectItem * newEraseRect = new QGraphicsRectItem(QRectF(lastPoint, QSizeF(drawingPen.width()+5, drawingPen.width()+5)), 0, getDrawingData());
                currentItem = newEraseRect;
                newEraseRect->setPen(QPen(Qt::transparent));
                newEraseRect->setBrush(QBrush(Qt::white));
            }

            else if(state == DRAWINGSTATE_UPDATE) {
                QGraphicsRectItem * newEraseRect = new QGraphicsRectItem(currentItem, getDrawingData());
                newEraseRect->setRect(QRectF(lastPoint, QSizeF(drawingPen.width()+5, drawingPen.width()+5)));
                newEraseRect->setPen(QPen(Qt::transparent));
                newEraseRect->setBrush(QBrush(Qt::white));
            }

            else {
                QGraphicsRectItem * newEraseRect = new QGraphicsRectItem(currentItem, getDrawingData());
                newEraseRect->setRect(QRectF(lastPoint, QSizeF(drawingPen.width()+5, drawingPen.width()+5)));
                newEraseRect->setPen(QPen(Qt::transparent));
                newEraseRect->setBrush(QBrush(Qt::white));
                // remove the temporary QGraphicsItem
                getDrawingData()->removeItem(currentItem);
             }
            // common in all cases for the eraser:
            // we have to set a specific composition mode for the eraser
            // back up the current value
            prevCompMode = picturePainter.compositionMode();
            picturePainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
            // fill the region to be erased with transparent color
            picturePainter.fillRect(QRectF(lastPoint, QSizeF(drawingPen.width()+5, drawingPen.width()+5)),Qt::transparent);
            // restore the old composition mode
            picturePainter.setCompositionMode(prevCompMode);
            break;

        case DRAWINGMODE_ARROW:
            // TODO not yet implemented - implement this as well
        break;

    }

    if(state == DRAWINGSTATE_END) {
        // finalize the painting on the QPicture
        picturePainter.end();
        commitDrawing(picture);
    }
}
Exemplo n.º 16
0
TlinearChart::TlinearChart(Texam* exam, Tchart::Tsettings& settings, QWidget* parent) :
    TmainChart(exam, settings, parent)
{
// Determine y value type and its maximal value to prepare Y axis
  switch (settings.yValue) {
    case TmainLine::e_prepareTime: {
      quint32 prepTime = 0;
      for(int i = 0; i < exam->count(); i++)
        prepTime = qMax(prepTime, exam->question(i)->attempt(0)->prepareTime());
      yAxis->setMaxValue((qreal)prepTime / 10.0);
      yAxis->setUnit(TYaxis::e_prepareTime);
      break;
    }
    case TmainLine::e_attemptsCount: {
      int attemptsNr = 0;
      for(int i = 0; i < exam->count(); i++)
        attemptsNr = qMax(attemptsNr, exam->question(i)->attemptsCount());
      yAxis->setMaxValue(attemptsNr, false);
      yAxis->setUnit(TYaxis::e_attemptsCount);
      break;
    }
    case TmainLine::e_playedCount: {
      int playedNr = 0;
      for(int i = 0; i < exam->count(); i++)
        playedNr = qMax(playedNr, exam->question(i)->totalPlayBacks());
      yAxis->setMaxValue(playedNr, false);
      yAxis->setUnit(TYaxis::e_playedCount);
      break;
    }
    case TmainLine::e_effectiveness: {
      yAxis->setMaxValue(100.0); // 100% looks good for this kind
      yAxis->setUnit(TYaxis::e_effectiveness);
      break;
    }
    default: {
      quint16 maxTime = 0;
      for(int i = 0; i < exam->count(); i++)
        maxTime = qMax(maxTime, exam->question(i)->time);
      yAxis->setMaxValue((qreal)maxTime / 10.0);
      break;
    }
  }
  
	if (settings.order == e_byNumber) {
		xAxis->setAnswersList(currExam->answList(), currExam->level());
		prepareChart(currExam->count());
		m_mainLine = new TmainLine(currExam->answList(), this, settings.yValue);
		if (settings.yValue == TmainLine::e_questionTime) {
			qreal aTime = 0 , prev = 0;
			int firstCorrect = 0, okCount = 0;
			for(int i = 0; i < exam->count(); i++) { // looking for first correct answer
				if (!exam->question(i)->isWrong() || (!exam->question(i)->isWrong() && settings.inclWrongAnsw)) {
					firstCorrect = i;
					prev = exam->question(i)->time;
					okCount++;
					aTime = prev;
					break;
				}
			}
      int prevX = firstCorrect + 1;
      for(int i = firstCorrect + 1; i < exam->count(); i++) {
        if (exam->question(i)->isWrong())
          continue; // skip wrong answers in aver time
        else 
          aTime = (aTime * okCount + (exam->question(i)->time)) / (okCount + 1);
        
        okCount++;
        TgraphicsLine *averProgress = new TgraphicsLine();
        scene->addItem(averProgress);
        averProgress->setPen(QPen(averColor.darker(120), 3, Qt::DotLine));
        averProgress->setLine(xAxis->mapValue(prevX) + xAxis->pos().x(), yAxis->mapValue(prev / 10.0),
                              xAxis->mapValue(i + 1) + xAxis->pos().x(), yAxis->mapValue(aTime / 10.0));
        prevX = i + 1;
        averProgress->setZValue(20);
        prev = aTime;
      }
      
      if (exam->averageReactonTime() > 0) {
          TgraphicsLine *averLine = new TgraphicsLine(0, "<p>" +
              TexTrans::averAnsverTimeTxt() + 
              QString("<br><big><b>%1</b></big></p>").arg(Texam::formatReactTime(exam->averageReactonTime(), true)) );
          scene->addItem(averLine);
          averLine->setZValue(15);
          averLine->setPen(QPen(averColor, 2));
          averLine->setLine(xAxis->mapValue(1) + xAxis->pos().x(), yAxis->mapValue(exam->averageReactonTime() / 10.0),
              xAxis->mapValue(exam->count()) + xAxis->pos().x(), yAxis->mapValue(exam->averageReactonTime() / 10.0));
      }
  // rest of cases are available only for melodies
		}
  }
  
  if (settings.order == e_byNote || settings.order == e_byFret ||
          settings.order == e_byKey || settings.order == e_byAccid || 
          settings.order == e_byQuestAndAnsw || settings.order == e_byMistake) {
      sort();
      xAxis->setAnswersLists(sortedLists, exam->level());
      int ln = 0;
      for (int i = 0; i < sortedLists.size(); i++)
        ln += sortedLists[i].size();
      prepareChart(ln);
      m_mainLine = new TmainLine(sortedLists, this, settings.yValue);
      
      int goodOffset = 0; // 0 when not unrelated question list inside
      if (hasListUnrelated)
        goodOffset = -1; // do not perform a last loop 
      int cnt = 1;
      if (settings.yValue != TmainLine::e_questionTime) {
        QTimer::singleShot(10, this, SLOT(ajustChartHeight()));
        return;
      }
  // paint lines with average time of all the same notes/frets
     for (int i = 0; i < goodSize + goodOffset; i++) { // skip wrong answers if separated
        if (sortedLists[i].size() > 1) {
        TgraphicsLine *averTimeLine = new TgraphicsLine(&sortedLists[i]);

        averTimeLine->setText(sortedLists[i].fullDescription());
        scene->addItem(averTimeLine);
        averTimeLine->setZValue(46);
        averTimeLine->setPen(QPen(averColor, 3)); // sea blue
        averTimeLine->setLine(xAxis->mapValue(cnt - 0.4) + xAxis->pos().x(), yAxis->mapValue(sortedLists[i].averTime() / 10.0),
          xAxis->mapValue(cnt + sortedLists[i].size() -0.6) + xAxis->pos().x(), yAxis->mapValue(sortedLists[i].averTime() / 10.0));
        }
        cnt += sortedLists[i].size();
      }
      cnt = 1;
      // paint highlights under grouped items
      for (int i = 0; i < sortedLists.size(); i++) {
          QGraphicsRectItem *groupBg = new QGraphicsRectItem();
          scene->addItem(groupBg);
          QColor hiCol = palette().highlight().color();
          hiCol.setAlpha(60);
          if (i%2) {
            groupBg->setBrush(QBrush(hiCol));
            groupBg->setPen(Qt::NoPen);
            groupBg->setRect(xAxis->mapValue(cnt), 0, sortedLists[i].size() * xAxis->questWidth(), yAxis->boundingRect().height());
            groupBg->setZValue(-1);
          }
          cnt += sortedLists[i].size();
      }
  // fret number over the chart
    if (settings.order == e_byFret) {
      cnt = 1;
      for (int i = 0; i < goodSize; i++) { 
        QGraphicsTextItem *fretText = getTextItem(30);
        QString hintText = "<b>";
        if (goodOffset && (i == goodSize -1))
          hintText += QApplication::translate("TlinearChart", "questions unrelated<br>with chart type");
        else
          hintText += QString("%1").arg(TfingerPos::romanFret(sortedLists[i].first()->qa.pos.fret()));
        hintText += "</b>";
        fretText->setHtml(hintText);
				TgraphicsTextTip::alignCenter(fretText);
				qreal sc = 1.0;
        if (sortedLists[i].size() * xAxis->questWidth() < fretText->boundingRect().width()) {
            sc = (sortedLists[i].size() * xAxis->questWidth()) / fretText->boundingRect().width();
            fretText->setScale(sc);
        }
        fretText->setPos(xAxis->mapValue(cnt) + 
        (sortedLists[i].size() * xAxis->questWidth() - fretText->boundingRect().width() * sc) / 2,
                         yAxis->mapValue(yAxis->maxValue()));        
        
        cnt += sortedLists[i].size();
      }      
    }
  // key signature names over the chart
    if (settings.order == e_byKey) {
      cnt = 1;
      QColor tc = palette().text().color();
      for (int i = 0; i < goodSize; i++) { 
        QGraphicsTextItem *keyText = getTextItem(16);
        QString hintText = "<b>";
        if (goodOffset && (i == goodSize -1))
          hintText += QApplication::translate("TlinearChart", "questions unrelated<br>with chart type");
        else {
            hintText += QString("%1").arg(sortedLists[i].first()->key.getName());
            hintText += "<br>" + getWasInAnswOrQuest(TQAtype::e_asNote, sortedLists[i].operator[](0).qaPtr);
        }
        hintText += "</b>";
        keyText->setHtml(hintText);
				TgraphicsTextTip::alignCenter(keyText);
        qreal sc = 1.0;
        if (sortedLists[i].size() * xAxis->questWidth() < keyText->boundingRect().width()) {
            sc = (sortedLists[i].size() * xAxis->questWidth()) / keyText->boundingRect().width();
            keyText->setScale(sc);
        }
        keyText->setPos(xAxis->mapValue(cnt) + 
        (sortedLists[i].size() * xAxis->questWidth() - keyText->boundingRect().width() * sc) / 2, 
                         yAxis->mapValue(yAxis->maxValue()));        
        cnt += sortedLists[i].size();
      }
    }
// accidentals over the chart
    if (settings.order == e_byAccid) {
      cnt = 1;
      for (int i = 0; i < goodSize; i++) { 
        QGraphicsTextItem *accidentalText = getTextItem(30);
        QString hintText;
        if (goodOffset && (i == goodSize -1))
          hintText += QApplication::translate("TlinearChart", "questions unrelated<br>with chart type") + "</span>";
        else 
          if (kindOfAccids[i])
            hintText += QString("%1").arg(accidToNotka(kindOfAccids[i], 40));
          else
            hintText += QApplication::translate("TlinearChart", "without accidentals");
        accidentalText->setHtml(hintText);
				TgraphicsTextTip::alignCenter(accidentalText);
        accidentalText->setPos(xAxis->mapValue(cnt) + 
        (sortedLists[i].size() * xAxis->questWidth() - accidentalText->boundingRect().width()) / 2, 
                         yAxis->mapValue(yAxis->maxValue()));        
        cnt += sortedLists[i].size();
      }      
    }
  // question/answer type over the chart
		if (settings.order == e_byQuestAndAnsw) {
			cnt = 1;
			for (int i = 0; i < goodSize; i++) { 
        QGraphicsTextItem *qaText = getTextItem(30);
				int nootFontSize = fontMetrics().boundingRect("A").height() * 2;
        QString hintText;
				if (exam->melodies()) {
					if (sortedLists[i].first()->questionAs == TQAtype::e_asNote)
						hintText = TexTrans::playMelodyTxt();
					else
						hintText = TexTrans::writeMelodyTxt();
				} else
					hintText = TnooFont::span(TquestionAsWdg::qaTypeSymbol(sortedLists[i].first()->questionAs) + "?", nootFontSize) + 
							"<br>" + TnooFont::span(TquestionAsWdg::qaTypeSymbol(sortedLists[i].first()->answerAs) + "!", nootFontSize);
        qaText->setHtml(hintText);
				TgraphicsTextTip::alignCenter(qaText);
				qreal sc = 1.0;
        if (sortedLists[i].size() * xAxis->questWidth() < qaText->boundingRect().width()) {
            sc = (sortedLists[i].size() * xAxis->questWidth()) / qaText->boundingRect().width();
            qaText->setScale(sc);
        }
        qaText->setPos(xAxis->mapValue(cnt) + 
        (sortedLists[i].size() * xAxis->questWidth() - qaText->boundingRect().width() * sc) / 2, 
                         yAxis->mapValue(0) - yAxis->length());        
        cnt += sortedLists[i].size();
      }
		}  
  }
  QTimer::singleShot(10, this, SLOT(ajustChartHeight()));
}