void NonPdfCropping::createWidgets(QGraphicsScene &scene)
{
  const double MARGIN_PERCENT = 5.0;
  const int ZERO_WIDTH_IS_ALWAYS_VISIBLE = 0;

  int marginHor = scene.width()  * MARGIN_PERCENT / 100.0;
  int marginVer = scene.height() * MARGIN_PERCENT / 100.0;

  QRect box (scene.sceneRect().left() + marginHor,
             scene.sceneRect().top()  + marginVer,
             scene.sceneRect().width() - 2 * marginHor,
             scene.sceneRect().height() - 2 * marginVer);

  m_handleTL = new NonPdfFrameHandle (scene, m_view, box.topLeft()    , NON_PDF_CROPPING_LEFT   | NON_PDF_CROPPING_TOP    , *this, Z_HANDLE);
  m_handleTR = new NonPdfFrameHandle (scene, m_view, box.topRight()   , NON_PDF_CROPPING_RIGHT  | NON_PDF_CROPPING_TOP    , *this, Z_HANDLE);
  m_handleBR = new NonPdfFrameHandle (scene, m_view, box.bottomRight(), NON_PDF_CROPPING_RIGHT  | NON_PDF_CROPPING_BOTTOM , *this, Z_HANDLE);
  m_handleBL = new NonPdfFrameHandle (scene, m_view, box.bottomLeft() , NON_PDF_CROPPING_LEFT   | NON_PDF_CROPPING_BOTTOM , *this, Z_HANDLE);

  m_box = new QGraphicsRectItem;
  m_box->setZValue (Z_BOX);
  m_box->setPen (QPen (QBrush (Qt::gray), ZERO_WIDTH_IS_ALWAYS_VISIBLE));
  scene.addItem (m_box);

  updateBox ();
}
示例#2
0
void BSplineVisDialog::on_printButton_clicked() {
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save PDF File"), "/tmpfs", tr("PDF File (*.pdf)"));
    
    if (fileName.isNull()) {
        return;
    }

    QGraphicsScene printerScene;
    renderScene(printerScene, true);
    
    QPrinter printer(QPrinter::HighResolution);
    QSizeF paperSize;
    paperSize.setWidth(printerScene.sceneRect().width());
    paperSize.setHeight(printerScene.sceneRect().height());
    printer.setPaperSize(paperSize, QPrinter::Millimeter);
    printer.setPageMargins(5, 5, 5, 5, QPrinter::Millimeter);
    printer.setOrientation(QPrinter::Portrait);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(fileName);


    QPainter painter(&printer);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::NonCosmeticDefaultPen);
    printerScene.render(&painter);
    painter.end();
}
示例#3
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    iScore1(0), iScore2(0)
{
    ui->setupUi(this);

    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setSceneRect(0, 0, ui->boardView->size().width()-30, ui->boardView->size().height()-30);

    QGraphicsRectItem *p1 = new QGraphicsRectItem(0, 0, 20, 80);
    p1->setBrush(QBrush(Qt::blue));
    QGraphicsRectItem *p2 = new QGraphicsRectItem(0, 0, 20, 80);
    p2->setBrush(QBrush(Qt::green));

    QGraphicsEllipseItem *ball = new QGraphicsEllipseItem(0, 0, 15, 15);
    ball->setBrush(QBrush(Qt::magenta));

    ui->boardView->setScene(scene);

    iLoop = new Gameplay(*scene, p1, p2, ball, this);
    QSize m(scene->sceneRect().size().width() + 10, scene->sceneRect().size().height() + 10);
    ui->boardView->setMinimumSize(m);
    ui->boardView->installEventFilter(iLoop);

    QObject::connect(iLoop, SIGNAL(goal(int)),
                     this, SLOT(addScore(int)));


    panel =  new ControlPanel(this);
    connect(panel, SIGNAL(pointsReady(std::vector<glm::vec2>)), iLoop, SLOT(setPoints(std::vector<glm::vec2>)));

    panel->show();
}
示例#4
0
void UIDebugVDP1::on_lwCommandList_itemSelectionChanged ()
{
   int cursel = lwCommandList->currentRow();
   char tempstr[1024];

   Vdp1DebugCommand(cursel, tempstr);
   pteCommandInfo->clear();
   pteCommandInfo->appendPlainText(QtYabause::translate(tempstr));
   pteCommandInfo->moveCursor(QTextCursor::Start);

   if (vdp1texture)
      free(vdp1texture);

   vdp1texture = Vdp1DebugTexture(cursel, &vdp1texturew, &vdp1textureh);
   pbSaveBitmap->setEnabled(vdp1texture ? true : false);

   // Redraw texture
   QGraphicsScene *scene = gvTexture->scene();
   QImage img((uchar *)vdp1texture, vdp1texturew, vdp1textureh, QImage::Format_ARGB32);
   QPixmap pixmap = QPixmap::fromImage(img.rgbSwapped());
   scene->clear();
   scene->addPixmap(pixmap);
   scene->setSceneRect(scene->itemsBoundingRect());
   gvTexture->fitInView(scene->sceneRect());
   gvTexture->invalidateScene();
}
示例#5
0
void UIDebugVDP2Viewer::on_cbScreen_currentIndexChanged ( int index )
{   
	if (!Vdp2Regs)
		return;

   if (vdp2texture)
      free(vdp2texture);

   vdp2texture = Vdp2DebugTexture(index, &width, &height);
   pbSaveAsBitmap->setEnabled(vdp2texture ? true : false);

   // Redraw screen
   QGraphicsScene *scene = gvScreen->scene();
#ifdef USE_RGB_555
   QImage img((uchar *)vdp2texture, width, height, QImage::Format_RGB555);
#elif USE_RGB_565
   QImage img((uchar *)vdp2texture, width, height, QImage::Format_RGB16);
#else
   QImage img((uchar *)vdp2texture, width, height, QImage::Format_ARGB32);
#endif
   QPixmap pixmap = QPixmap::fromImage(img.rgbSwapped());
   scene->clear();
   scene->addPixmap(pixmap);
   scene->setSceneRect(scene->itemsBoundingRect());
   gvScreen->fitInView(scene->sceneRect());
   gvScreen->invalidateScene();
}
示例#6
0
void MainWindow::SetBackground(float opacity)
{
    QGraphicsScene* newScene = new QGraphicsScene(pixmap->rect());

    QImage alpha(pixmap->size(), QImage::Format_ARGB32_Premultiplied);
    alpha.fill(Qt::transparent);
    QPainter p(&alpha);
    p.setOpacity(opacity);
    p.drawPixmap(0, 0, *pixmap);
    p.end();

    newScene->addPixmap(QPixmap::fromImage(alpha));

    ui->graphicsView->setScene(newScene);
    ui->graphicsView->fitInView(newScene->sceneRect(), Qt::KeepAspectRatio);
    ui->graphicsView->show();

    if(scene != 0)
    {
        scene->clear();
        delete scene;
    }
    scene = newScene;

}
示例#7
0
QRectF SegmentList::rect() const {
   QGraphicsScene scene;
   foreach(Segment const * const segment, *this) {
      scene.addItem(segment->toQGraphicsItem());
      // without the following line QPainter tends to crash
      scene.width();
   }
   return scene.sceneRect();
}
int main(int argc, char **argv)
{
    Q_INIT_RESOURCE(stickman);
    QApplication app(argc, argv);

    StickMan *stickMan = new StickMan;
    stickMan->setDrawSticks(false);

    QGraphicsTextItem *textItem = new QGraphicsTextItem();
    textItem->setHtml("<font color=\"white\"><b>Stickman</b>"
        "<p>"
        "Tell the stickman what to do!"
        "</p>"
        "<p><i>"
        "<li>Press <font color=\"purple\">J</font> to make the stickman jump.</li>"
        "<li>Press <font color=\"purple\">D</font> to make the stickman dance.</li>"
        "<li>Press <font color=\"purple\">C</font> to make him chill out.</li>"
        "<li>When you are done, press <font color=\"purple\">Escape</font>.</li>"
        "</i></p>"
        "<p>If he is unlucky, the stickman will get struck by lightning, and never jump, dance or chill out again."
        "</p></font>");
    qreal w = textItem->boundingRect().width();
    QRectF stickManBoundingRect = stickMan->mapToScene(stickMan->boundingRect()).boundingRect();
    textItem->setPos(-w / 2.0, stickManBoundingRect.bottom() + 25.0);

    QGraphicsScene scene;
    scene.addItem(stickMan);

    scene.addItem(textItem);
    scene.setBackgroundBrush(Qt::black);

    GraphicsView view;
    view.setRenderHints(QPainter::Antialiasing);
    view.setTransformationAnchor(QGraphicsView::NoAnchor);
    view.setScene(&scene);

    QRectF sceneRect = scene.sceneRect();
    // making enough room in the scene for stickman to jump and die
    view.resize(sceneRect.width() + 100, sceneRect.height() + 100);
    view.setSceneRect(sceneRect);

    view.show();
    view.setFocus();

    LifeCycle cycle(stickMan, &view);
    cycle.setDeathAnimation(":/animations/dead.bin");

    cycle.addActivity(":/animations/jumping.bin", Qt::Key_J);
    cycle.addActivity(":/animations/dancing.bin", Qt::Key_D);
    cycle.addActivity(":/animations/chilling.bin", Qt::Key_C);

    cycle.start();


    return app.exec();
}
示例#9
0
void DeclarativeDragArea::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if ( !m_enabled
            || QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton)).length()
            < m_startDragDistance) {
        return;
    }

    emit dragStarted();

    QDrag *drag = new QDrag(event->widget());
    DeclarativeMimeData* dataCopy = new DeclarativeMimeData(m_data); //Qt will take ownership of this copy and delete it.
    drag->setMimeData(dataCopy);

    if (!m_delegateImage.isNull()) {
        drag->setPixmap(QPixmap::fromImage(m_delegateImage));
    } else if (m_delegate) {
        // Render the delegate to a Pixmap
        QDeclarativeItem* item = qobject_cast<QDeclarativeItem *>(m_delegate->create(m_delegate->creationContext()));

        QGraphicsScene scene;
        scene.addItem(item);

        QPixmap pixmap(scene.sceneRect().width(), scene.sceneRect().height());
        pixmap.fill(Qt::transparent);

        QPainter painter(&pixmap);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setRenderHint(QPainter::SmoothPixmapTransform);
        scene.render(&painter);
        painter.end();
        delete item;

        drag->setPixmap(pixmap);
    }

    drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height()/2)); // TODO: Make a property for that

    //setCursor(Qt::OpenHandCursor);    //TODO? Make a property for the cursor

    Qt::DropAction action = drag->exec(m_supportedActions, m_defaultAction);
    emit drop(action);
}
示例#10
0
void HorizontalView::showAll()
{
    QGraphicsScene* s = scene();
    if (s)
    {
        QRectF sceneRect = s->sceneRect();
        _viewStart = sceneRect.left();
        _viewEnd = sceneRect.right();
        updateTransformation();
    }
}
    virtual void resizeEvent(QResizeEvent *event) {
        QGraphicsView::resizeEvent(event);
        QGraphicsScene *scene = this->scene();
        if (scene) {
            QRectF newSceneRect(0, 0, event->size().width(), event->size().height());
            scene->setSceneRect(newSceneRect);
            if (scene->sceneRect().size() != event->size()) {
                QSizeF from(scene->sceneRect().size());
                QSizeF to(event->size());
                QTransform transform;
                transform.scale(to.width() / from.width(), to.height() / from.height());
                setTransform(transform);
            } else {
                resetTransform();
            }
            setSceneRect(scene->sceneRect());
        }

        MainWindow *main_window = qobject_cast<MainWindow *>(parentWidget());
        if (main_window)
            main_window->fitBackgroundBrush();
    }
示例#12
0
void SceneInspector::initializeGui()
{
    if (!Endpoint::isConnected()) {
        // only do something if we are connected to a remote client
        return;
    }

    QGraphicsScene *scene = m_sceneModel->scene();
    if (!scene)
        return;

    emit sceneRectChanged(scene->sceneRect());
}
示例#13
0
文件: main.cpp 项目: RSATom/Qt
int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QGraphicsScene scene;
    QGraphicsView view(&scene);

    Knob *knob1 = new Knob;
    knob1->setPos(-110, 0);
    Knob *knob2 = new Knob;

    scene.addItem(knob1);
    scene.addItem(knob2);

    view.showMaximized();
    view.fitInView(scene.sceneRect().adjusted(-20, -20, 20, 20), Qt::KeepAspectRatio);

    return app.exec();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DREAM3DGraphicsView::setZoomIndex(int index)
{
  if (index == 9)
  {
    QGraphicsScene* scenePtr = scene();
    if (NULL != scenePtr)
    {
      QRectF r = scenePtr->sceneRect();
      fitInView(r, Qt::KeepAspectRatio);
    }
  }
  else
  {
    QTransform transform;
    transform.scale(m_ZoomFactors[index], m_ZoomFactors[index]);
    setTransform(transform);
  }

}
示例#15
0
void MyQGraphicsView::saveImage()
{
    QGraphicsScene *ascene = this->scene();
    ascene->clearSelection();                                                  // Selections would also render to the file
    ascene->setSceneRect(ascene->itemsBoundingRect());                          // Re-shrink the scene to it's bounding contents
    QImage image(ascene->sceneRect().size().toSize(), QImage::Format_ARGB32);  // Create the image with the exact size of the shrunk scene
    image.fill(Qt::transparent);                                              // Start all pixels transparent
    QPainter painter(&image);
    ascene->render(&painter);
//    char filename[] = "view.png";
//    ifield++;
//    char numstr[5];
//    sprintf(numstr,"%04d",hour);
//    for (int i=0; i<4; i++)
//        filename[11+i] = numstr[i];
    QString fileName = QFileDialog::getSaveFileName(this, tr("Image File Name"), ".", tr("Image Files (*.png)"));
    if (fileName.compare("") != 0) {
        image.save(fileName);
    }
}
示例#16
0
//virtual
void VirtualCamera::setup(const QGraphicsItem * farBoundItem,const QList<QPointer<ThingPaintable> >& exclusionList,
							const QRectF& sceneViewport)
{
	m_triggerAble = false;
	//grab the scene pointer, or bail if not available
	QGraphicsScene * pScene = DimensionsGlobal::globalGraphicsScene();
	if (!pScene)
	{
		qDebug() << __FUNCTION__ << ": global graphics scene not available";
		return;
	}

	QList<QGraphicsItem *> rawItems;
	QSize rectSize;
	//if the sceneViewport isn't empty, then just get the items that are w/in it
	// use Qt::IntersectsItemBoundingRect to speed things up; this doesn't have to be exact, since the actual render by
	// trigger() will have to deal with source regions anyways
	if (!sceneViewport.isEmpty())
	{
		rectSize = sceneViewport.size().toSize();
		if ((rectSize.width() == 0) || (rectSize.height() == 0))
		{
			//would cause problems later
			m_viewport = QRectF();
			return;
		}
		m_viewport = sceneViewport;
		rawItems = pScene->items(sceneViewport,Qt::IntersectsItemBoundingRect,Qt::AscendingOrder);
		//SHOULD be ok to convert toSize(), w.r.t. trunc-ing off decimal bits and getting a smaller whole size
		// painter will have to do a similar thing so it SHOULD be compatible.
		// if things crash, look here first!
	}
	else //else get everything
	{
		rectSize = pScene->sceneRect().size().toSize();
		if ((rectSize.width() == 0) || (rectSize.height() == 0))
		{
			m_viewport = QRectF();
			return;
		}
		m_viewport = pScene->sceneRect();
		rawItems = pScene->items(pScene->sceneRect(),Qt::IntersectsItemBoundingRect,Qt::AscendingOrder);
	}

	//re-init the excludes
	m_excludes = QSet<QPointer<ThingPaintable> >::fromList(exclusionList);
	//clear the subjects
	m_subjects.clear();

	//the list is in ascending stack order. Toss out anything:
	// 1. below the farBoundItem
	// 2. not a ThingPaintable
	// 3. in the exclusion list

	//can't directly use "visible" as a determinant; the scene *can* provide an indicator of whether or not an item is occluded.
	// However, tossing out items by 1,2,3, above may actually reveal an item that was previously occluded, so more complicated logic
	// would be needed. It's ok though. The likelihood of it giving a significant reduction is minimal against the expense to
	// determine it.

	bool farItemReached = (farBoundItem == 0 ? true : false);		//if no far item was specified then set as already reached
	for (QList<QGraphicsItem *>::iterator it = rawItems.begin();
			it != rawItems.end();++it)
	{
		QGraphicsItem * pItem = *it;
		if ((!pItem) || (!farItemReached))
		{
			continue;
		}
		if (pItem == farBoundItem)
		{
			farItemReached = true;
		}
		ThingPaintable * pThingPaintable = ThingPaintable::thingpaintable_cast(pItem);
		if (!pThingPaintable)
		{
			continue;
		}
		if (m_excludes.contains(QPointer<ThingPaintable>(pThingPaintable)))
		{
			qDebug() << __FUNCTION__ << ": excluding thingpaintable [" << pThingPaintable->objectName() << "]";
			continue;
		}
		//ok it made it through the gauntlet...append to subjects list
		m_subjects << QPointer<ThingPaintable>(pThingPaintable);
	}

	//if the subjects list contains anything, then set up a pixmapobject...
	if (m_subjects.isEmpty())
	{
		//nada...bail
		m_viewport = QRectF();
		return;
	}

	setupBackingFb(pScene->sceneRect().size().toSize());
	m_triggerAble = true;
}
示例#17
0
文件: main.cpp 项目: Afreeca/qt
int main(int argc, char **argv)
{
    Q_INIT_RESOURCE(stickman);
    QApplication app(argc, argv);

    StickMan *stickMan = new StickMan;
    stickMan->setDrawSticks(false);

#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5) || defined(Q_WS_SIMULATOR)
    RectButton *buttonJump = new RectButton("Jump"); buttonJump->setPos(100, 125);
    RectButton *buttonDance = new RectButton("Dance"); buttonDance->setPos(100, 200);
    RectButton *buttonChill = new RectButton("Chill"); buttonChill->setPos(100, 275);
#else
    QGraphicsTextItem *textItem = new QGraphicsTextItem();
    textItem->setHtml("<font color=\"white\"><b>Stickman</b>"
        "<p>"
        "Tell the stickman what to do!"
        "</p>"
        "<p><i>"
        "<li>Press <font color=\"purple\">J</font> to make the stickman jump.</li>"
        "<li>Press <font color=\"purple\">D</font> to make the stickman dance.</li>"
        "<li>Press <font color=\"purple\">C</font> to make him chill out.</li>"
        "<li>When you are done, press <font color=\"purple\">Escape</font>.</li>"
        "</i></p>"
        "<p>If he is unlucky, the stickman will get struck by lightning, and never jump, dance or chill out again."
        "</p></font>");
    qreal w = textItem->boundingRect().width();
    QRectF stickManBoundingRect = stickMan->mapToScene(stickMan->boundingRect()).boundingRect();
    textItem->setPos(-w / 2.0, stickManBoundingRect.bottom() + 25.0);
#endif

    QGraphicsScene scene;
    scene.addItem(stickMan);

#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5) || defined(Q_WS_SIMULATOR)
    scene.addItem(buttonJump);
    scene.addItem(buttonDance);
    scene.addItem(buttonChill);
#else
    scene.addItem(textItem);
#endif
    scene.setBackgroundBrush(Qt::black);

    GraphicsView view;
    view.setRenderHints(QPainter::Antialiasing);
    view.setTransformationAnchor(QGraphicsView::NoAnchor);
    view.setScene(&scene);

    QRectF sceneRect = scene.sceneRect();
    // making enough room in the scene for stickman to jump and die
    view.resize(sceneRect.width() + 100, sceneRect.height() + 100);
    view.setSceneRect(sceneRect);

#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5) || defined(Q_WS_SIMULATOR)
    view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view.showMaximized();
    view.fitInView(scene.sceneRect(), Qt::KeepAspectRatio);
#else
    view.show();
    view.setFocus();
#endif

    LifeCycle cycle(stickMan, &view);
    cycle.setDeathAnimation(":/animations/dead");

#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5) || defined(Q_WS_SIMULATOR)
    cycle.addActivity(":/animations/jumping", Qt::Key_J, buttonJump, SIGNAL(clicked()));
    cycle.addActivity(":/animations/dancing", Qt::Key_D, buttonDance, SIGNAL(clicked()));
    cycle.addActivity(":/animations/chilling", Qt::Key_C, buttonChill, SIGNAL(clicked()));
#else
    cycle.addActivity(":/animations/jumping", Qt::Key_J);
    cycle.addActivity(":/animations/dancing", Qt::Key_D);
    cycle.addActivity(":/animations/chilling", Qt::Key_C);
#endif

    cycle.start();


    return app.exec();
}
示例#18
0
//! [0]
PadNavigator::PadNavigator(const QSize &size, QWidget *parent)
    : QGraphicsView(parent)
{
//! [0]
//! [1]
    // Splash item
    SplashItem *splash = new SplashItem;
    splash->setZValue(1);
//! [1]

//! [2]
    // Pad item
    FlippablePad *pad = new FlippablePad(size);
    QGraphicsRotation *flipRotation = new QGraphicsRotation(pad);
    QGraphicsRotation *xRotation = new QGraphicsRotation(pad);
    QGraphicsRotation *yRotation = new QGraphicsRotation(pad);
    flipRotation->setAxis(Qt::YAxis);
    xRotation->setAxis(Qt::YAxis);
    yRotation->setAxis(Qt::XAxis);
    pad->setTransformations(QList<QGraphicsTransform *>()
                            << flipRotation
                            << xRotation << yRotation);
//! [2]

//! [3]
    // Back (proxy widget) item
    QGraphicsProxyWidget *backItem = new QGraphicsProxyWidget(pad);
    QWidget *widget = new QWidget;
    form.setupUi(widget);
    form.hostName->setFocus();
    backItem->setWidget(widget);
    backItem->setVisible(false);
    backItem->setFocus();
    backItem->setCacheMode(QGraphicsItem::ItemCoordinateCache);
    const QRectF r = backItem->rect();
    backItem->setTransform(QTransform()
                           .rotate(180, Qt::YAxis)
                           .translate(-r.width()/2, -r.height()/2));
//! [3]

//! [4]
    // Selection item
    RoundRectItem *selectionItem = new RoundRectItem(QRectF(-60, -60, 120, 120), Qt::gray, pad);
    selectionItem->setZValue(0.5);
//! [4]

//! [5]
    // Splash animations
    QPropertyAnimation *smoothSplashMove = new QPropertyAnimation(splash, "y");
    QPropertyAnimation *smoothSplashOpacity = new QPropertyAnimation(splash, "opacity");
    smoothSplashMove->setEasingCurve(QEasingCurve::InQuad);
    smoothSplashMove->setDuration(250);
    smoothSplashOpacity->setDuration(250);
//! [5]

//! [6]
    // Selection animation
    QPropertyAnimation *smoothXSelection = new QPropertyAnimation(selectionItem, "x");
    QPropertyAnimation *smoothYSelection = new QPropertyAnimation(selectionItem, "y");
    QPropertyAnimation *smoothXRotation = new QPropertyAnimation(xRotation, "angle");
    QPropertyAnimation *smoothYRotation = new QPropertyAnimation(yRotation, "angle");
    smoothXSelection->setDuration(125);
    smoothYSelection->setDuration(125);
    smoothXRotation->setDuration(125);
    smoothYRotation->setDuration(125);
    smoothXSelection->setEasingCurve(QEasingCurve::InOutQuad);
    smoothYSelection->setEasingCurve(QEasingCurve::InOutQuad);
    smoothXRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothYRotation->setEasingCurve(QEasingCurve::InOutQuad);
//! [6]

//! [7]
    // Flip animation setup
    QPropertyAnimation *smoothFlipRotation = new QPropertyAnimation(flipRotation, "angle");
    QPropertyAnimation *smoothFlipScale = new QPropertyAnimation(pad, "scale");
    QPropertyAnimation *smoothFlipXRotation = new QPropertyAnimation(xRotation, "angle");
    QPropertyAnimation *smoothFlipYRotation = new QPropertyAnimation(yRotation, "angle");
    QParallelAnimationGroup *flipAnimation = new QParallelAnimationGroup(this);
    smoothFlipScale->setDuration(500);
    smoothFlipRotation->setDuration(500);
    smoothFlipXRotation->setDuration(500);
    smoothFlipYRotation->setDuration(500);
    smoothFlipScale->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipXRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipYRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipScale->setKeyValueAt(0, qvariant_cast<qreal>(1.0));
    smoothFlipScale->setKeyValueAt(0.5, qvariant_cast<qreal>(0.7));
    smoothFlipScale->setKeyValueAt(1, qvariant_cast<qreal>(1.0));
    flipAnimation->addAnimation(smoothFlipRotation);
    flipAnimation->addAnimation(smoothFlipScale);
    flipAnimation->addAnimation(smoothFlipXRotation);
    flipAnimation->addAnimation(smoothFlipYRotation);
//! [7]

//! [8]
    // Flip animation delayed property assignment
    QSequentialAnimationGroup *setVariablesSequence = new QSequentialAnimationGroup;
    QPropertyAnimation *setFillAnimation = new QPropertyAnimation(pad, "fill");
    QPropertyAnimation *setBackItemVisibleAnimation = new QPropertyAnimation(backItem, "visible");
    QPropertyAnimation *setSelectionItemVisibleAnimation = new QPropertyAnimation(selectionItem, "visible");
    setFillAnimation->setDuration(0);
    setBackItemVisibleAnimation->setDuration(0);
    setSelectionItemVisibleAnimation->setDuration(0);
    setVariablesSequence->addPause(250);
    setVariablesSequence->addAnimation(setBackItemVisibleAnimation);
    setVariablesSequence->addAnimation(setSelectionItemVisibleAnimation);
    setVariablesSequence->addAnimation(setFillAnimation);
    flipAnimation->addAnimation(setVariablesSequence);
//! [8]

//! [9]
    // Build the state machine
    QStateMachine *stateMachine = new QStateMachine(this);
    QState *splashState = new QState(stateMachine);
    QState *frontState = new QState(stateMachine);
    QHistoryState *historyState = new QHistoryState(frontState);
    QState *backState = new QState(stateMachine);
//! [9]
//! [10]
    frontState->assignProperty(pad, "fill", false);
    frontState->assignProperty(splash, "opacity", 0.0);
    frontState->assignProperty(backItem, "visible", false);
    frontState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(0.0));
    frontState->assignProperty(selectionItem, "visible", true);
    backState->assignProperty(pad, "fill", true);
    backState->assignProperty(backItem, "visible", true);
    backState->assignProperty(xRotation, "angle", qvariant_cast<qreal>(0.0));
    backState->assignProperty(yRotation, "angle", qvariant_cast<qreal>(0.0));
    backState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(180.0));
    backState->assignProperty(selectionItem, "visible", false);
    stateMachine->addDefaultAnimation(smoothXRotation);
    stateMachine->addDefaultAnimation(smoothYRotation);
    stateMachine->addDefaultAnimation(smoothXSelection);
    stateMachine->addDefaultAnimation(smoothYSelection);
    stateMachine->setInitialState(splashState);
//! [10]

//! [11]
    // Transitions
    QEventTransition *anyKeyTransition = new QEventTransition(this, QEvent::KeyPress, splashState);
    anyKeyTransition->setTargetState(frontState);
    anyKeyTransition->addAnimation(smoothSplashMove);
    anyKeyTransition->addAnimation(smoothSplashOpacity);
//! [11]

//! [12]
    QKeyEventTransition *enterTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                   Qt::Key_Enter, backState);
    QKeyEventTransition *returnTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                    Qt::Key_Return, backState);
    QKeyEventTransition *backEnterTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                       Qt::Key_Enter, frontState);
    QKeyEventTransition *backReturnTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Return, frontState);
    enterTransition->setTargetState(historyState);
    returnTransition->setTargetState(historyState);
    backEnterTransition->setTargetState(backState);
    backReturnTransition->setTargetState(backState);
    enterTransition->addAnimation(flipAnimation);
    returnTransition->addAnimation(flipAnimation);
    backEnterTransition->addAnimation(flipAnimation);
    backReturnTransition->addAnimation(flipAnimation);
//! [12]

//! [13]
    // Create substates for each icon; store in temporary grid.
    int columns = size.width();
    int rows = size.height();
    QVector< QVector< QState * > > stateGrid;
    stateGrid.resize(rows);
    for (int y = 0; y < rows; ++y) {
        stateGrid[y].resize(columns);
        for (int x = 0; x < columns; ++x)
            stateGrid[y][x] = new QState(frontState);
    }
    frontState->setInitialState(stateGrid[0][0]);
    selectionItem->setPos(pad->iconAt(0, 0)->pos());
//! [13]

//! [14]
    // Enable key navigation using state transitions
    for (int y = 0; y < rows; ++y) {
        for (int x = 0; x < columns; ++x) {
            QState *state = stateGrid[y][x];
            QKeyEventTransition *rightTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                           Qt::Key_Right, state);
            QKeyEventTransition *leftTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Left, state);
            QKeyEventTransition *downTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Down, state);
            QKeyEventTransition *upTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Up, state);
            rightTransition->setTargetState(stateGrid[y][(x + 1) % columns]);
            leftTransition->setTargetState(stateGrid[y][((x - 1) + columns) % columns]);
            downTransition->setTargetState(stateGrid[(y + 1) % rows][x]);
            upTransition->setTargetState(stateGrid[((y - 1) + rows) % rows][x]);
//! [14]
//! [15]
            RoundRectItem *icon = pad->iconAt(x, y);
            state->assignProperty(xRotation, "angle", -icon->x() / 6.0);
            state->assignProperty(yRotation, "angle", icon->y() / 6.0);
            state->assignProperty(selectionItem, "x", icon->x());
            state->assignProperty(selectionItem, "y", icon->y());
            frontState->assignProperty(icon, "visible", true);
            backState->assignProperty(icon, "visible", false);

            QPropertyAnimation *setIconVisibleAnimation = new QPropertyAnimation(icon, "visible");
            setIconVisibleAnimation->setDuration(0);
            setVariablesSequence->addAnimation(setIconVisibleAnimation);
        }
    }
//! [15]

//! [16]
    // Scene
    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setBackgroundBrush(QPixmap(":/images/blue_angle_swirl.jpg"));
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    scene->addItem(pad);
    scene->setSceneRect(scene->itemsBoundingRect());
    setScene(scene);
//! [16]

//! [17]
    // Adjust splash item to scene contents
    const QRectF sbr = splash->boundingRect();
    splash->setPos(-sbr.width() / 2, scene->sceneRect().top() - 2);
    frontState->assignProperty(splash, "y", splash->y() - 100.0);
    scene->addItem(splash);
//! [17]

//! [18]
    // View
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setMinimumSize(50, 50);
    setViewportUpdateMode(FullViewportUpdate);
    setCacheMode(CacheBackground);
    setRenderHints(QPainter::Antialiasing
                   | QPainter::SmoothPixmapTransform
                   | QPainter::TextAntialiasing);
#ifndef QT_NO_OPENGL
    setViewport(new QOpenGLWidget);
#endif

    stateMachine->start();
//! [18]
}
示例#19
0
//-----------------------------------------------------------------------------------------
// New version, site/cell size is fixed, the blob grows
//-----------------------------------------------------------------------------------------
void Field::displayField(int hr, int *res)
{
    QGraphicsScene* scene = new QGraphicsScene(QRect(0, 0, CANVAS_WIDTH, CANVAS_WIDTH));
    QBrush brush;
    int i, xindex, yindex, ix, iy, w, rgbcol[3];
    double xp, yp, d0, d, volume, scale, cmin, cmax, rmax;
    double a, b, Wc;
    int Nc;
    bool growthRate;

//    LOG_MSG("displayField");
    *res = 0;
    hour = hr;
	if (slice_changed) {
        get_fieldinfo(&NX, &axis, &fraction, &nsites, &nconst, const_used, res);
        if (*res != 0) return;
        this->data = (FIELD_DATA *)malloc(nsites*sizeof(FIELD_DATA));
        get_fielddata(&axis, &fraction, &nsites, &nconst, this->data, res);
        if (*res != 0) return;
        slice_changed = false;
    }

    if (constituent == GROWTH_RATE)
        growthRate = true;
    else
        growthRate = false;

    if (axis == X_AXIS) {           // Y-Z plane
        xindex = 1;
        yindex = 2;
    } else if (axis == Y_AXIS) {   // X-Z plane
        xindex = 0;
        yindex = 2;
    } else if (axis == Z_AXIS) {   // X-Y plane
        xindex = 0;
        yindex = 1;
    }

/*
 NX = size of lattice
 Nc = # of sites to fill the canvas from side to side (or top to bottom) = (2/3)NX
 Wc = canvas width (pixels)
 w = site width = Wc/Nc
 xp = a.ix + b
 yp = a.iy + b
 blob centre at (NX/2,NX/2) maps to canvas centre at (Wc/2,Wc/2)
 => Wc/2 = a.NX/2 + b
 The width of Nc sites maps to the canvas width
 => Wc = a.Nc
 => a = Wc/Nc, b = Wc/2 - a.NX/2
*/
    Nc = (2*NX)/3;
    Wc = CANVAS_WIDTH;
    w = Wc/Nc;
    a = w;
    b = Wc/2 - a*NX/2;
    d0 = w*dfraction;
    cmin = 1.0e10;
    cmax = 0;
    rmax = 0;
    for (i=0; i<nsites; i++) {
        rmax = MAX(rmax,data[i].dVdt);
        cmin = MIN(MAX(cmin,0),data[i].conc[constituent]);
        cmax = MAX(cmax,data[i].conc[constituent]);
    }
    brush.setStyle(Qt::SolidPattern);
    brush.setColor(QColor(0,0,0));
    scene->addRect(0,0,CANVAS_WIDTH,CANVAS_WIDTH,Qt::NoPen, brush);
    view->setScene(scene);
    view->setGeometry(QRect(0, 0, 700, 700));
    if (cmax == 0) {
        view->show();
        return;
    }

    for (i=0; i<nsites; i++) {
        ix = this->data[i].site[xindex];
        iy = this->data[i].site[yindex];
        xp = int(a*ix + b - w);
        yp = int(a*iy + b - w);
        chooseFieldColor(data[i].conc[constituent],cmin,cmax,use_log,rgbcol);
        brush.setColor(QColor(rgbcol[0],rgbcol[1],rgbcol[2]));
        scene->addRect(xp,yp,w,w,Qt::NoPen, brush);
    }

    for (i=0; i<nsites; i++) {
        ix = this->data[i].site[xindex];
        iy = this->data[i].site[yindex];
        xp = int(a*ix + b - w);
        yp = int(a*iy + b - w);
        volume = this->data[i].volume;      // = 0 if there is no cell
        if (volume > 0) {
            scale = pow(volume,0.3333);
            d = scale*d0;   // fix this - need to change d0
            double f;
            if (rmax > 0) {
                f = data[i].dVdt/rmax;
            } else {
                f = 0.01;
            }
            chooseRateColor(f,rgbcol);
            brush.setColor(QColor(rgbcol[0],rgbcol[1],rgbcol[2]));
            scene->addEllipse(xp+(w-d)/2,yp+(w-d)/2,d,d,Qt::NoPen, brush);
        }
    }
    view->show();
    if (save_images) {
        scene->clearSelection();                                                  // Selections would also render to the file
        scene->setSceneRect(scene->itemsBoundingRect());                          // Re-shrink the scene to it's bounding contents
        QImage image(scene->sceneRect().size().toSize(), QImage::Format_ARGB32);  // Create the image with the exact size of the shrunk scene
        image.fill(Qt::transparent);                                              // Start all pixels transparent

        QPainter painter(&image);
        scene->render(&painter);
        ifield++;
        char filename[] = "image/field0000.png";
        char numstr[5];
        sprintf(numstr,"%04d",hour);
        for (int i=0; i<4; i++)
            filename[11+i] = numstr[i];
        image.save(filename);
    }
}
示例#20
0
 QRectF deviceRect() const {
   return _scene->sceneRect();
 }
void SceneImageExporter::PageGraphicsSceneToPrinter(QGraphicsScene *scene, QPrinter &printer,
                                                    QList<SectorRectHolder>& pageRegions, QString fileName,
                                                    QString documentName __attribute__((unused)))
{
    PrintingPreferences &pref  __attribute__ ((unused))  = PrintingPreferences::prefs();
    //qDebug()  << pref.yDivisions();
    //qDebug()  << pref.selectedMeasure();
    //qDebug() << pref.measures();

    if (!fileName.isEmpty() && fileName != "" && fileName.endsWith(".pdf",Qt::CaseInsensitive))
    {
        printer.setOutputFormat(QPrinter::PdfFormat);
        printer.setOutputFileName(fileName);
    }

    // When printing, use full page mode, IE ignore hardware margins. It's up
    // to users to set them as they desire.
    printer.setFullPage(true);
    printer.setPaperSize(QSizeF(PrintingPreferences::prefs().selectedMeasure().width(),
                                PrintingPreferences::prefs().selectedMeasure().height()),
                         QPrinter::Millimeter);
    printer.setPageMargins(PrintingPreferences::prefs().leftMargin(),
                           PrintingPreferences::prefs().topMargin(),
                           PrintingPreferences::prefs().rightMargin(),
                           PrintingPreferences::prefs().bottomMargin(),
                           QPrinter::Millimeter);

    //here, I print using selected sheets and divisions.
    QPainter painter(&printer);
    qreal left,top,right,bottom;
    printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel);

    // get the FULL PAGE RECTANGLE and adjust margins.
    QRectF pageRect = printer.paperRect();
    pageRect.adjust(left,top,-right, -bottom);


    QColor transparent(0,0,0,0);
    QColor transBorder (0,0,0,128);
    QPen pen (transBorder);
    pen.setStyle(Qt::DotLine);
    QBrush brush;

    QGraphicsScene sceneFirst;
    QPen pen2 (QColor(0,0,0));
    pen2.setStyle(Qt::DotLine);
    pen2.setWidthF(2.0);
    QBrush brush2;
    for (int h = 0; h < pageRegions.count(); h++)
    {
        QRectF rect = pageRegions[h].rectInner();
        sceneFirst.addRect (rect.left(), rect.top(), rect.width(),rect.height(),pen2, brush2);
        rect = pageRegions[h].rectOuter();
        sceneFirst.addRect (rect.left(), rect.top(), rect.width(),rect.height(),pen2, brush2);
    }
    scene->render(&painter, pageRect, scene->itemsBoundingRect(),Qt::KeepAspectRatio);
    sceneFirst.render(&painter,pageRect, sceneFirst.sceneRect(),Qt::KeepAspectRatio);


    for (int h = 0; h < pageRegions.count(); h++)
    {
        QRectF rect = pageRegions[h].rectOuter();
        double ratio = rect.width()/rect.height();
        QRectF rectTarget = QRectF(pageRect.left(), pageRect.top(), pageRect.width(), pageRect.width()/ratio);
        printer.newPage();
        scene->render(&painter,rectTarget, rect);
        painter.setPen(pen2);
        painter.setBrush(brush);
        painter.drawRect(rectTarget);
        QRectF rect2 = pageRegions[h].rectInner();
        double ratioX = rectTarget.width()/rect.width();
        double ratioY = rectTarget.height()/rect.height();

        double dy = rect2.top()-rect.top();
        double dx = rect2.left() - rect.left();

        //qDebug() << "rect outer: " << rect
        //        <<  "\nrect inner: " << rect2
        //        << "\nrect target: " << rectTarget
        //        << "\nx: " << dx << ",y:" << dy;

        QRectF rectTarget2 (rectTarget.top()+ dx*ratioX,
                            rectTarget.left()+dy*ratioY,
                            rect2.width()*ratioX,
                            rect2.height()*ratioY);
        painter.drawRect(rectTarget2);

    }
    painter.end();
}
示例#22
0
int main(int argc, char *argv[])
{
    // Инициализируем генератор псевдослучайных чисел
    qsrand(QTime::currentTime().msec());

    QApplication app(argc, argv);

    BubbleItem::setBubblePixmap(QPixmap(":/images/bubble.png"));

    // Получаем скриншот
    QScreen *screen = QApplication::primaryScreen();
    if (!screen)
        return -1;
    QPixmap screenshot = screen->grabWindow(0);

    // QGraphicsScene - контейнер для создаваемых нами
    // объектов класса Bubble
    QGraphicsScene scene;
    scene.setSceneRect( screenshot.rect() );

    // Наполняем сцену непересекающимися элементами
    {
        const int left   = scene.sceneRect().left()   + BubbleItem::RADIUS;
        const int top    = scene.sceneRect().top()    + BubbleItem::RADIUS;
        const int right  = scene.sceneRect().right()  - BubbleItem::RADIUS;
        const int bottom = scene.sceneRect().bottom() - BubbleItem::RADIUS;

        for (int i = 0; i < BUBBLES_AMOUNT; ++i)
        {
            BubbleItem *bubble = new BubbleItem();
            scene.addItem(bubble);

            // Будем давать пузырю случайные координаты до тез пор
            // пока он не прекратит пересекаться с другими пузырями
            do
            {
                bubble->setPos(
                    left + qrand() % (right - left),
                    top  + qrand() % (bottom - top)
                );
            }
            while ( !scene.collidingItems(bubble).isEmpty() );
        }
    }

    // MainWidget - главный и единственный виджет этой программы,
    // он непосредственно рисует на экране элементы сцены, а также
    // обрабатывает нажатие клавиш и завершает выполнение программы при
    // нажатии клавиши ESC
    MainWidget view(&scene);
    view.setBackgroundPixmap(screenshot);
    view.setRenderHint(QPainter::Antialiasing);
    view.showFullScreen();

    // Используем QTimer для анимации движения пузырей. Сцена будет принудительно
    // обновляться EXPECTED_FPS раз в секунду
    QTimer timer;
    QObject::connect(&timer, SIGNAL(timeout()), &scene, SLOT(advance()));
    timer.start(1000 / EXPECTED_FPS);

    return app.exec();
}