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); }
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); } }
void Run::setup(QGraphicsView* viewGrid) { p_Grid = new Grid(20,20,this); turnNumber = 0; // Begin timekeeping QGraphicsRectItem * gridFrameOuter = new QGraphicsRectItem(95,95,210,210); QGraphicsRectItem * gridFrameInner = new QGraphicsRectItem(100,100,200,200); gridFrameInner->setBrush(QBrush(Qt::lightGray)); gridFrameOuter->setBrush(QBrush(Qt::gray)); QGraphicsRectItem * countFrameOuter = new QGraphicsRectItem(95, 305, 210, 50); countFrameOuter->setBrush(QBrush(Qt::darkCyan)); viewGrid->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); viewGrid->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); viewGrid->show(); p_Grid->p_scene->addItem(gridFrameOuter); p_Grid->p_scene->addItem(gridFrameInner); p_Grid->p_scene->addItem(countFrameOuter); p_Grid->placeDoodlebugs(5); p_Grid->placeAnts(100); r_numAnts = new QGraphicsTextItem; setAnts(getNumAnts()); r_numAnts->setPos(100, 305); r_numDoodleBugs = new QGraphicsTextItem; setDbugs(getNumDoodleBugs()); r_numDoodleBugs->setPos(100, 330); p_Grid->p_scene->addItem(r_numDoodleBugs); p_Grid->p_scene->addItem(r_numAnts); }
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); } } }
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); #ifdef SUBSURFACE_MOBILE label->setPos(x + 1, -2.5); #endif label->setZValue(101); }
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); } }
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)); }
void DataVisualizer::draw(SceneType scene, qreal& lastXPos, Element::Ptr e, int propertyIndex) { if (e.isNull()) return; // see if item should be drawn Element::Property p(Element::getProperty(propertyIndex)); Element::PropertyType type(Element::propertyType(p)); Element::PropertyVariant var(e->propertyConst(p)); if (p == Element::NUCLEONS_PROPERTY && !e->isIsotope()) return; if (!Element::isValidVariant(var)) return; // build the text item QGraphicsItem * item(0); QGraphicsTextItem * text = new QGraphicsTextItem(); text->setHtml( getLinkText(*e) + "<br>" + mMainWindow->toString(var)); text->setTextInteractionFlags(Qt::TextBrowserInteraction); text->setToolTip(tr("formattedFormulaToolTip")); connect(text, SIGNAL(linkActivated(const QString&)), this, SLOT(emitElementLinkActivated(const QString&))); item = text; // build the encapsulating box item QGraphicsRectItem * rect = new QGraphicsRectItem( item->boundingRect() ); rect->setBrush(QBrush(QColor(196, 255, 196))); // combine both and add them to the scene item->setParentItem(rect); scene->addItem(rect); QPointF pos(boost::apply_visitor(DrawingPositionFromPropertyVariant(), var)); if (type == Element::COMPLEX_TYPE || type == Element::STRING_TYPE) { // no stacking for 2D drawing // item positions are stretched in X direction if (lastXPos > pos.x()) { pos.setX(lastXPos); } rect->setPos(pos); // update drawing position for the next item lastXPos = pos.x() + rect->boundingRect().width() + itemMargin; } else { setItemPos(rect, pos); } }
//----------------------------------------------------------------------------- // 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_); }
/////////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; }
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; }
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); }
QGraphicsItemGroup* MainWindow::createVisualNodo(string* names, int cant){ QGraphicsItemGroup* grupo = new QGraphicsItemGroup(); int posx = 0; int dim = 50; for(int x = 0; x < cant; x++){ QGraphicsRectItem* cuadro = new QGraphicsRectItem(posx,0,50,50); cuadro->setBrush(QBrush(Qt::gray)); QGraphicsTextItem* texto = new QGraphicsTextItem(); texto->setPos(posx, dim/3); texto->setPlainText(QString::fromStdString(names[x])); grupo->addToGroup(cuadro); grupo->addToGroup(texto); posx+=dim; } return grupo; }
void GamePlay::displayGameOver(int highScore) { for (size_t i = 0, n=scene->items().size();i<n;i++) scene->items()[i]->setEnabled(false); timer->stop(); QGraphicsRectItem *panel = new QGraphicsRectItem(160,120,300,320); QBrush brush; brush.setStyle(Qt::SolidPattern); brush.setColor(Qt::yellow); panel->setBrush(brush); panel->setOpacity(0.65); scene->addItem(panel); QGraphicsTextItem *gameOverText = new QGraphicsTextItem(QString("GAME OVER!\nYour score:")+QString::number(highScore)); gameOverText->setDefaultTextColor(Qt::magenta); gameOverText->setFont(QFont("Pixelette",20)); gameOverText->setPos(185,160); scene->addItem(gameOverText); }
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; }
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 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)); }
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 info_item::init() { QFont f; f.setPixelSize(20); QBrush brush; brush.setStyle(Qt::SolidPattern); brush.setColor(Qt::black); // Draw rect information QGraphicsRectItem* r = new QGraphicsRectItem(0, 0, AMD_SCENE_WIDTH, 30); r->setBrush(brush); addToGroup(r); // Draw life addToGroup(new core::life(0, QPoint(5, 5))); life_text_ = new QGraphicsTextItem(); life_text_->setFont(f); life_text_->setPos(30, 0); life_text_->setTextWidth(70); life_text_->setDefaultTextColor(QColor(Qt::white)); addToGroup(life_text_); // Draw text world / level place_text_ = new QGraphicsTextItem(); place_text_->setFont(f); place_text_->setPos(100, 0); place_text_->setTextWidth(600); place_text_->setDefaultTextColor(QColor(Qt::white)); addToGroup(place_text_); // Draw id world / level addToGroup(new core::egg(0, QPoint(705, 5))); egg_text_ = new QGraphicsTextItem(); egg_text_->setFont(f); egg_text_->setPos(730, 0); egg_text_->setTextWidth(70); egg_text_->setDefaultTextColor(QColor(Qt::white)); addToGroup(egg_text_); }
void VisualMatrix::initSprite() { _sprite = new QGraphicsWidget(); QGraphicsItem* item; QGraphicsWidget* widget; QGraphicsRectItem* rect; QGraphicsColorizeEffect* effect; QGraphicsSimpleTextItem* text; QGraphicsProxyWidget* proxy; QLabel* label; QFont font; // Frame { item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_FRAME_BG)); item->setParentItem(_sprite); item->setPos(0.0f, 0.0f); } // Frame { item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_FRAME_MG)); item->setParentItem(_sprite); item->setPos(0.0f, 0.0f); } // Avatar { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 10, BLOCK_LARGE * 20); widget->setFlags(QGraphicsItem::ItemClipsChildrenToShape); widget->setParentItem(_sprite); widget->setPos(170.0f, 50.0f); item = new QGraphicsPixmapItem(); item->setParentItem(widget); item->setPos(((BLOCK_LARGE * 10) - (320.0f / 0.75f)) * 0.5f, (BLOCK_LARGE * 20) - 320.0f); _avatar = widget; } // Help { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 10, BLOCK_LARGE * 20); widget->setFlags(QGraphicsItem::ItemClipsChildrenToShape); widget->setParentItem(_sprite); widget->setPos(170.0f, 50.0f); rect = new QGraphicsRectItem(0.0f, 0.0f, BLOCK_LARGE * 10, BLOCK_LARGE * 20); rect->setBrush(QBrush(QColor::fromRgb(0x00, 0x00, 0x00, 0xC0))); rect->setParentItem(widget); font = QApplication::font(); font.setFamily("Arial"); font.setPixelSize(16); font.setWeight(QFont::Bold); font.setStretch(80); text = new QGraphicsSimpleTextItem(tr("Slide left and right: Move.")); text->setBrush(QColor::fromRgb(0xC0, 0xC0, 0xC0)); text->setFont(font); text->setParentItem(widget); text->setPos(((BLOCK_LARGE * 10) - text->boundingRect().width()) * 0.5f, 217.0f - 6.0f); text = new QGraphicsSimpleTextItem(tr("Swipe up: Hold. Swipe down: Drop.")); text->setBrush(QColor::fromRgb(0xC0, 0xC0, 0xC0)); text->setFont(font); text->setParentItem(widget); text->setPos(((BLOCK_LARGE * 10) - text->boundingRect().width()) * 0.5f, 237.0f - 6.0f); text = new QGraphicsSimpleTextItem(tr("Pull back, and make circles: Rotate.")); text->setBrush(QColor::fromRgb(0xC0, 0xC0, 0xC0)); text->setFont(font); text->setParentItem(widget); text->setPos(((BLOCK_LARGE * 10) - text->boundingRect().width()) * 0.5f, 257.0f - 6.0f); // widget->setVisible(false); _sprite_help = widget; } // Lines { rect = new QGraphicsRectItem(120.0f - 1.0f, 220.0f - 1.0f, 8.0f + 2.0f, 144.0f + 2.0f); rect->setBrush(QBrush(LoaderThread::instance()->getCachedPixmap(IMAGE_LINES_PROGRESS))); rect->setParentItem(_sprite); _sprite_lines = rect; } // Frame { item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_FRAME_FG)); item->setParentItem(_sprite); item->setPos(0.0f, 0.0f); } // Field { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 10, BLOCK_LARGE * 20); widget->setFlags(QGraphicsItem::ItemClipsChildrenToShape); widget->setParentItem(_sprite); widget->setPos(170.0f, 50.0f); _sprite_field = widget; _sprite_space.fill(NULL, _rows * _cols); } // Ghost { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 4, BLOCK_LARGE * 4); widget->setParentItem(_sprite_field); widget->setPos(BLOCK_LARGE * getShapePositionInField(18, 3)); for (int i = 0; i < 4; ++i) { item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_BLOCK_GHOST)); item->setParentItem(widget); } _sprite_ghost = widget; } // Tetromino { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 4, BLOCK_LARGE * 4); widget->setParentItem(_sprite_field); widget->setPos(BLOCK_LARGE * getShapePositionInField(18, 3)); widget->setZValue(1.0f); effect = new QGraphicsColorizeEffect(widget); effect->setColor(QColor::fromRgb(0xFF, 0xFF, 0xFF)); effect->setStrength(0.0f); widget->setGraphicsEffect(effect); for (int i = 0; i < 4; ++i) { item = new QGraphicsPixmapItem(); item->setParentItem(widget); } _sprite_tetromino = widget; } // Hold { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 4, BLOCK_LARGE * 2); widget->setScale(BLOCK_SMALL / BLOCK_LARGE); widget->setParentItem(_sprite); widget->setPos(56.0f, 108.0f + BLOCK_SMALL); effect = new QGraphicsColorizeEffect(widget); effect->setColor(QColor::fromRgb(0xFF, 0xFF, 0xFF)); effect->setStrength(0.0f); widget->setGraphicsEffect(effect); for (int i = 0; i < 4; ++i) { item = new QGraphicsPixmapItem(); item->setParentItem(widget); } _sprite_hold = widget; } // Hold fail { item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_FAIL)); item->setScale(BLOCK_SMALL / BLOCK_LARGE); item->setParentItem(_sprite); item->setPos(56.0f + (BLOCK_SMALL * 3), 108.0f + (BLOCK_SMALL * 3)); item->setVisible(false); _sprite_holdFail = item; } // Next { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 4, BLOCK_LARGE * 2); widget->setScale(BLOCK_SMALL / BLOCK_LARGE); widget->setParentItem(_sprite); widget->setPos(460.0f, 108.0f + BLOCK_SMALL); effect = new QGraphicsColorizeEffect(widget); effect->setColor(QColor::fromRgb(0xFF, 0xFF, 0xFF)); effect->setStrength(0.0f); widget->setGraphicsEffect(effect); for (int i = 0; i < 4; ++i) { item = new QGraphicsPixmapItem(); item->setParentItem(widget); } _sprite_next << widget; } // Next { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 4, BLOCK_LARGE * 2); widget->setScale(BLOCK_SMALL / BLOCK_LARGE); widget->setParentItem(_sprite); widget->setPos(460.0f, 228.0f + BLOCK_SMALL); effect = new QGraphicsColorizeEffect(widget); effect->setColor(QColor::fromRgb(0xFF, 0xFF, 0xFF)); effect->setStrength(0.0f); widget->setGraphicsEffect(effect); for (int i = 0; i < 4; ++i) { item = new QGraphicsPixmapItem(); item->setParentItem(widget); } _sprite_next << widget; } // Next { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 4, BLOCK_LARGE * 2); widget->setScale(BLOCK_SMALL / BLOCK_LARGE); widget->setParentItem(_sprite); widget->setPos(460.0f, 292.0f + BLOCK_SMALL); effect = new QGraphicsColorizeEffect(widget); effect->setColor(QColor::fromRgb(0xFF, 0xFF, 0xFF)); effect->setStrength(0.0f); widget->setGraphicsEffect(effect); for (int i = 0; i < 4; ++i) { item = new QGraphicsPixmapItem(); item->setParentItem(widget); } _sprite_next << widget; } // Font { font = QApplication::font(); font.setCapitalization(QFont::AllUppercase); } // Hold { text = new QGraphicsSimpleTextItem(tr("Hold")); text->setBrush(QColor::fromRgb(0x00, 0x00, 0x00)); text->setFont(font); text->setParentItem(_sprite); text->setPos(56.0f, 80.0f - 6.0f); } // Next { text = new QGraphicsSimpleTextItem(tr("Next")); text->setBrush(QColor::fromRgb(0x00, 0x00, 0x00)); text->setFont(font); text->setParentItem(_sprite); text->setPos(526.0f - text->boundingRect().width(), 80.0f - 6.0f); } // Level { text = new QGraphicsSimpleTextItem(tr("Level")); text->setBrush(QColor::fromRgb(0x00, 0x00, 0x00)); text->setFont(font); text->setParentItem(_sprite); text->setPos(56.0f, 316.0f - 6.0f); } // Level { label = new QLabel(); label->resize(48, 24); label->setStyleSheet("background-color: transparent; color: #FFFFFF;"); label->setAlignment(Qt::AlignTop | Qt::AlignLeft); proxy = new QGraphicsProxyWidget(); proxy->setParentItem(_sprite); proxy->setWidget(label); proxy->setPos(56.0f, 344.0f - 6.0f); _sprite_level = label; } // Score { text = new QGraphicsSimpleTextItem(tr("Score")); text->setBrush(QColor::fromRgb(0x00, 0x00, 0x00)); text->setFont(font); text->setParentItem(_sprite); text->setPos(176.0f, 564.0f - 6.0f); } // Score { label = new QLabel(); label->resize(148, 24); label->setStyleSheet("background-color: transparent; color: #FFFFFF;"); label->setAlignment(Qt::AlignTop | Qt::AlignRight); proxy = new QGraphicsProxyWidget(); proxy->setParentItem(_sprite); proxy->setWidget(label); proxy->setPos(256.0f, 564.0f - 6.0f); _sprite_score = label; } // Countdown { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 10, BLOCK_LARGE * 20); widget->setFlags(QGraphicsItem::ItemClipsChildrenToShape); widget->setParentItem(_sprite); widget->setPos(170.0f, 50.0f); rect = new QGraphicsRectItem(0.0f, 0.0f, BLOCK_LARGE * 10, BLOCK_LARGE * 20); rect->setBrush(QBrush(QColor::fromRgb(0x00, 0x00, 0x00, 0xC0))); rect->setParentItem(widget); item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_COUNT[0])); item->setParentItem(widget); item->setPos(77.0f, 197.0f); item->setVisible(false); _sprite_count << item; item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_COUNT[1])); item->setParentItem(widget); item->setPos(77.0f, 197.0f); item->setVisible(false); _sprite_count << item; item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_COUNT[2])); item->setParentItem(widget); item->setPos(77.0f, 197.0f); item->setVisible(false); _sprite_count << item; widget->setVisible(false); _sprite_countdown = widget; } // Game over { widget = new QGraphicsWidget(); widget->resize(BLOCK_LARGE * 10, BLOCK_LARGE * 20); widget->setFlags(QGraphicsItem::ItemClipsChildrenToShape); widget->setParentItem(_sprite); widget->setPos(170.0f, 50.0f); widget->setZValue(8.0f); rect = new QGraphicsRectItem(0.0f, 0.0f, BLOCK_LARGE * 10, BLOCK_LARGE * 20); rect->setBrush(QBrush(QColor::fromRgb(0x00, 0x00, 0x00, 0xC0))); rect->setParentItem(widget); item = new QGraphicsPixmapItem(LoaderThread::instance()->getCachedPixmap(IMAGE_OVER)); item->setParentItem(widget); item->setPos(4.0f, 172.0f); rect = new QGraphicsRectItem(0.0f, 0.0f, BLOCK_LARGE * 10, BLOCK_LARGE * 20); rect->setBrush(QBrush(QColor::fromRgb(0xFF, 0xFF, 0xFF))); rect->setParentItem(widget); _sprite_overFlash = rect; widget->setVisible(false); _sprite_over = widget; } }
void B2WorldView::createWorldItems() { qDebug() << "~ " << __PRETTY_FUNCTION__; if(_world && _scene) { // create world ground QGraphicsRectItem *groundItem = _scene->addRect(-100, -0.5, 200, 1); groundItem->setBrush(Qt::gray); groundItem->setPos(0, -0.5); // ground body define b2BodyDef groundBD; groundBD.type = b2_staticBody; groundBD.position.Set(0.0f, 0.5f); // ground shape define b2PolygonShape groundSD; groundSD.SetAsBox(100.0f, 0.5f, b2Vec2(0.0f, 0.0f), 0); // ground fixture define b2FixtureDef groundFD; groundFD.shape = &groundSD; groundFD.density = 0.1f; groundFD.friction = 5.0f; b2Body* groundBody = _world->CreateBody(&groundBD); groundBody->CreateFixture(&groundFD); groundItem = _scene->addRect(-1.0, -2.0, 2.0, 4.0); groundItem->setBrush(Qt::blue); groundItem->setPos(-100.0, -1.0); groundSD.SetAsBox(1.0f, 2.0f, b2Vec2(-100.0f, 0.5f), 0); groundBody->CreateFixture(&groundFD); groundItem = _scene->addRect(-1.0, -2.0, 2.0, 4.0); groundItem->setBrush(Qt::blue); groundItem->setPos(100.0, -0.5); groundSD.SetAsBox(1.0f, 2.0f, b2Vec2(100.0f, 1.0f), 0); groundBody->CreateFixture(&groundFD); groundItem = _scene->addRect(-3.0, -0.5, 6.0, 1.0); groundItem->setBrush(Qt::blue); groundItem->setPos(5, -2.0); groundItem->setRotation(-(PI / 4.0 * 360.0) / (2 * PI)); groundSD.SetAsBox(3.0f, 0.5f, b2Vec2(5.0f, 1.5f), PI/4.0); groundBody->CreateFixture(&groundFD); groundItem = _scene->addRect(-3.0, -0.5, 6.0, 1.0); groundItem->setBrush(Qt::blue); groundItem->setPos(3.5, -1.5); groundItem->setRotation(-(PI / 8.0 * 360.0) / (2 * PI)); groundSD.SetAsBox(3.0f, 0.5f, b2Vec2(3.5f, 1.0f), PI/8.0); groundBody->CreateFixture(&groundFD); groundItem = _scene->addRect(-3.0, -0.5, 6, 1.0); groundItem->setBrush(Qt::blue); groundItem->setPos(9, -2.0); groundItem->setRotation(-(-PI / 4.0 * 360.0) / (2 * PI)); groundSD.SetAsBox(3.0f, 0.5f, b2Vec2(9.0f, 1.5f), -PI/4.0); groundBody->CreateFixture(&groundFD); groundItem = _scene->addRect(-3, -0.5, 6, 1.0); groundItem->setBrush(Qt::blue); groundItem->setPos(10.5, -1.5); groundItem->setRotation(-(-PI / 8.0 * 360.0) / (2 * PI)); groundSD.SetAsBox(3.0f, 0.5f, b2Vec2(10.5f, 1.0f), -PI/8.0); groundBody->CreateFixture(&groundFD); // add random shit // b2CircleShape circleShape; b2FixtureDef circleFixture; circleFixture.shape = &circleShape; circleFixture.density = 0.01; circleFixture.friction = 0.1; circleFixture.restitution = 0.5; for (int i = 0; i < 30; i++) { qreal radius = qrand()%20*0.01+0.02; QGraphicsEllipseItem* circle = _scene->addEllipse(-radius, -radius, radius*2, radius*2); circle->setBrush(Qt::green); circle->setPos(qrand()%35+15.0, -1.5); _circles << circle; circleShape.m_radius = radius; b2BodyDef circleBD; circleBD.type = b2_dynamicBody; circleBD.position.Set(circle->pos().x(), -circle->pos().y()); circleBD.allowSleep = true; circleBD.linearDamping = 0.1; circleBD.angularDamping = 0.1; b2Body* circleBody = _world->CreateBody(&circleBD); circleBody->CreateFixture(&circleFixture); _circleBodies << circleBody; } // create kart _kart = new B2Kart(_world, _scene); } }
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; }
MainWindow::MainWindow(const ConfigLoader& configLoader, QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow), _programSettings(configLoader.getProgramSettings()) { bool isOk; // Initialize the Scene Data file - this copies a spare copy if the file is missing // in the Standard Folders path try { _sceneDataFile = SceneDataFile::getInstance(_programSettings.datafile.path, _programSettings.datafile.name, this); } catch (SceneDataFileException& exception) { throw exception; } // Load logo image from a resource file ResourceFileManager resourceFileManager(_programSettings.resourcefile.path); QByteArray buffer = resourceFileManager.loadFrom(_programSettings.resourcefile.name, _programSettings.logoImageFileName); if (buffer.isEmpty()) { qDebug() << "Unable to load: " + _programSettings.logoImageFileName + " from resource: " + _programSettings.resourcefile.name + " in path: " + _programSettings.resourcefile.path; } else { _pixmapLogo.loadFromData(buffer); } // Program settings: Load program setting from persistant storage _programSettingsPersistant = new QSettings(this); // UI: Setup UI ui->setupUi(this); setWindowTitle(QString("%1 " + tr("Initializing...")) .arg(_programSettings.application.name)); // UI: Setup indicators display area _scene = new CGraphicsScene(this); ui->graphicsView->setScene(_scene); QString imageFilePath = ASSETS_PATH + _programSettings.backgroundImageFileName; QImage imageBackgroundImage(ASSETS_PATH + _programSettings.backgroundImageFileName); if (imageBackgroundImage.isNull()) { qDebug() << "Background image failed to load: " + imageFilePath; } ui->graphicsView->setBackgroundBrush(QBrush(QColor(50, 50, 50))); QRect sceneRect(0, 0, imageBackgroundImage.width(), imageBackgroundImage.height()); QGraphicsRectItem* sceneRectItemBackground = _scene->addRect(sceneRect); sceneRectItemBackground->setBrush(QBrush(imageBackgroundImage)); // UI: Load indicators _listIndicatorProperties = configLoader.getIndicatorProperties(); for (IndicatorProperties currentIndicatorProperties: _listIndicatorProperties) { TemperatureIndicator* temperatureIndicator = new TemperatureIndicator(currentIndicatorProperties, _programSettings, ui->listWidget_Sensors, _scene); temperatureIndicator->setPosition(currentIndicatorProperties.position); temperatureIndicator->update(); QString key = QString::number(temperatureIndicator->getSensorId()); if (_programSettingsPersistant->contains(key)) { qreal temperature = _programSettingsPersistant->value(key).toDouble(); temperatureIndicator->setTemperatureTarget(temperature); } else { temperatureIndicator->setTemperatureTarget(currentIndicatorProperties.temperatureTarget); _programSettingsPersistant->setValue(key, temperatureIndicator->getTemperatureTarget()); } _temperatureIndicators.push_back(temperatureIndicator); } for (auto indicator: _temperatureIndicators) { isOk = connect(indicator, SIGNAL(doubleClicked(QGraphicsSceneMouseEvent*)), this, SLOT(onTemperatureIndicatorDoubleClicked(QGraphicsSceneMouseEvent*))); Q_ASSERT(isOk); Q_UNUSED(isOk); } _currentTemperatureIndicator = _temperatureIndicators[0]; _currentTemperatureIndicator->setIndicatorSelected(true); updateDialByCurrentTemperatureIndicator(); // UI: Connect QListWidget signal to TemperatureIndicators isOk = connect(ui->listWidget_Sensors, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onListWidgetItemClicked(QListWidgetItem*))); Q_ASSERT(isOk); Q_UNUSED(isOk); isOk = connect(ui->listWidget_Sensors, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(onListWidgetItemDoubleClicked(QListWidgetItem*))); Q_ASSERT(isOk); Q_UNUSED(isOk); // NOTE: SceneDataModel object has to be created after all _temperatureIndicators // have been loaded from config.xml as SceneDataModel uses getSensors() to // retrieve a list of all sensors. // All available sensors on the remote controller need to be defined in config.xml _sceneDataModel = new SceneDataModel(_sceneDataFile->getSceneDataFilePath(), _sceneDataFile->getSceneDataFileName(), this); this->listWidget_Scenes_Update(); #ifdef USE_NETWORKING // TcpSocket: Setup connectSocket(); #endif }
CalendarGraphicsItem::CalendarGraphicsItem(CalendarControl * cc, QGraphicsItem * parent) : QGraphicsRectItem(0.0, 0.0, __width, __height, parent) { _controller = cc; QDate today = QDate::currentDate(); QDate firstMonthDay = QDate(today.year(), today.month(), 1); QDate firstCalendarDay = firstMonthDay.addDays(firstMonthDay.dayOfWeek() * -1); if(firstMonthDay.dayOfWeek() < 2) firstCalendarDay = firstCalendarDay.addDays(-7); _selectedDay = today; QString prev = QObject::tr("<"); QString prevprev = QObject::tr("<<"); QString next = QObject::tr(">"); QString nextnext = QObject::tr(">>"); QGraphicsSimpleTextItem * textItem; QGraphicsRectItem * rectItem; rectItem = new QGraphicsRectItem(0.0, 0.0, __width, __titleHeight, this); rectItem->setBrush(blackFill); _items.insert("titleBackground", rectItem); textItem = new QGraphicsSimpleTextItem(today.toString("MMMM yyyy"), this); textItem->setFont(monthfont); textItem->setZValue(2); textItem->setBrush(whiteFill); QPointF ct = rectItem->boundingRect().center(); QRectF rt = textItem->boundingRect(); textItem->setPos(ct.x() - (rt.width() / 2), ct.y() - (rt.height() / 2)); _items.insert("title", textItem); qreal offset = 0.1 * __dpi; qreal nw = 0; GraphicsTextButtonItem * tbtnItem = 0; tbtnItem = new GraphicsTextButtonItem(prevprev, this); tbtnItem->setFont(navfont); tbtnItem->setZValue(3); tbtnItem->setBrush(Qt::lightGray); tbtnItem->setRolloverBrush(Qt::green); tbtnItem->scale(0.5, 1); tbtnItem->setReceiver(this); rt = tbtnItem->boundingRect(); tbtnItem->setPos(offset, ct.y() - (rt.height() / 2)); nw = rt.width(); _items.insert("fastrewind", tbtnItem); tbtnItem = new GraphicsTextButtonItem(nextnext, this); tbtnItem->setFont(navfont); tbtnItem->setZValue(3); tbtnItem->setBrush(Qt::lightGray); tbtnItem->setRolloverBrush(Qt::green); tbtnItem->scale(0.5, 1); tbtnItem->setReceiver(this); rt = tbtnItem->boundingRect(); tbtnItem->setPos(rectItem->boundingRect().right() - offset - (rt.width() / 2), ct.y() - (rt.height() / 2)); nw = qMax(nw, rt.width()) / 2; offset += (nw * 1.5); _items.insert("fastforward", tbtnItem); tbtnItem = new GraphicsTextButtonItem(prev, this); tbtnItem->setFont(navfont); tbtnItem->setZValue(3); tbtnItem->setBrush(Qt::lightGray); tbtnItem->setRolloverBrush(Qt::green); tbtnItem->scale(0.5, 1); tbtnItem->setReceiver(this); rt = tbtnItem->boundingRect(); tbtnItem->setPos(offset, ct.y() - (rt.height() / 2)); _items.insert("rewind", tbtnItem); tbtnItem = new GraphicsTextButtonItem(next, this); tbtnItem->setFont(navfont); tbtnItem->setZValue(3); tbtnItem->setBrush(Qt::lightGray); tbtnItem->setRolloverBrush(Qt::green); tbtnItem->scale(0.5, 1); tbtnItem->setReceiver(this); rt = tbtnItem->boundingRect(); tbtnItem->setPos(rectItem->boundingRect().right() - offset - (rt.width() / 2), ct.y() - (rt.height() / 2)); _items.insert("forward", tbtnItem); QDate date; qreal dayWidth = __width / 7.0; QApplication::setOverrideCursor(Qt::WaitCursor); for(int wday = 0; wday < 7; wday++) { for(int week = 0; week < 6; week++) { date = firstCalendarDay.addDays((7 * week) + wday); if(0 == week) { rectItem = new QGraphicsRectItem(wday * dayWidth, 0.5 * __dpi, dayWidth, 0.25 * __dpi, this); _items.insert(QString("weekday%1").arg(week), rectItem); textItem = new QGraphicsSimpleTextItem(date.toString("dddd"), this); textItem->setFont(wdayfont); textItem->setZValue(2); ct = rectItem->boundingRect().center(); rt = textItem->boundingRect(); textItem->setPos(ct.x() - (rt.width() / 2), ct.y() - (rt.height() / 2)); _items.insert(QString("weekday%1Text").arg(week), textItem); } QBrush fill; QBrush dayFill = blackFill; if(date == _selectedDay) fill = selectedFill; else if(date.month() != today.month()) { fill = nonMonthFill; dayFill = nonMonthDayFill; } else if(date == today) fill = todayFill; else if(date.dayOfWeek() > 5) fill = weekendFill; rectItem = new QGraphicsRectItem(wday * dayWidth, (0.75 + (1.25 * week)) * __dpi, dayWidth, 1.25 * __dpi, this); rectItem->setBrush(fill); _items.insert(QString("day%1").arg((7 * week) + wday), rectItem); rt = QRectF(rectItem->pos(), rectItem->boundingRect().size()); double offset = rt.width() / 3; textItem = new QGraphicsSimpleTextItem(QString::number(date.day()), this); textItem->setFont(dayfont); textItem->setZValue(2); textItem->setBrush(dayFill); textItem->setPos(rectItem->boundingRect().topLeft()); textItem->moveBy(5.0, 5.0); _items.insert(QString("day%1Number").arg((7 * week) + wday), textItem); rt = QRectF(textItem->pos(), textItem->boundingRect().size()); QString additionalText; if(_controller) additionalText = _controller->contents(date); textItem = new QGraphicsSimpleTextItem(additionalText, this); textItem->setFont(notesfont); textItem->setZValue(2); textItem->setBrush(dayFill); textItem->setPos(rt.left() + offset, rt.top() + (rt.height() * 1.5)); _items.insert(QString("day%1Text").arg((7 * week) + wday), textItem); } } QApplication::restoreOverrideCursor(); }
//CHARGEMENT DE LA MAP void myScene::charger_map(QString carte) { QString * path = new QString(*sourcePath); path->append(carte); int temp; int prev; int x_deb,y_deb; int i = 0; int x = 0; int y = 0; int elem[16][16]; //tableau temporaire pour conserver la configuration de la scène //DEFINITION DES ENTITES PARCELLES D'HERBE, PARCELLES DE BOUE, DIFFERENTS MORCEAUX DE CHEMIN, PANIER QGraphicsRectItem* rect; //récuperation des images QPixmap pix_boue (":/Terrain/boue.jpg"); QPixmap pix_herbe (":/Terrain/herbe.jpg"); QPixmap pix_panier (":/Terrain/panier.png"); QPixmap pix_N (":/Terrain/N.jpg"); QPixmap pix_NE (":/Terrain/N_E.jpg"); QPixmap pix_E (":/Terrain/N_E.jpg"); QPixmap pix_SE (":/Terrain/S_E.jpg"); QPixmap pix_S (":/Terrain/S.jpg"); QPixmap pix_SO (":/Terrain/S_O.jpg"); QPixmap pix_O (":/Terrain/O.jpg"); QPixmap pix_NO (":/Terrain/N_O.jpg"); //redimensionnement des images QPixmap pix_boue_scaled = pix_boue.scaled(35,35); QPixmap pix_herbe_scaled = pix_herbe.scaled(35,35); QPixmap pix_panier_scaled = pix_panier.scaled(35,35); QPixmap pix_N_scaled = pix_N.scaled(35,35); QPixmap pix_NE_scaled = pix_NE.scaled(35,35); QPixmap pix_E_scaled = pix_E.scaled(35,35); QPixmap pix_SE_scaled = pix_SE.scaled(35,35); QPixmap pix_S_scaled = pix_S.scaled(35,35); QPixmap pix_SO_scaled = pix_SO.scaled(35,35); QPixmap pix_O_scaled = pix_O.scaled(35,35); QPixmap pix_NO_scaled = pix_NO.scaled(35,35); //Definition des Brush QBrush panier (pix_panier_scaled); QBrush boue (pix_boue_scaled); QBrush herbe (pix_herbe_scaled); QBrush N (pix_N_scaled); QBrush NE (pix_NE_scaled); QBrush E (pix_E_scaled); QBrush SE (pix_SE_scaled); QBrush S (pix_S_scaled); QBrush SO (pix_SO_scaled); QBrush O (pix_O_scaled); QBrush NO (pix_NO_scaled); //on ouvre le fichier map.txt ifstream map((const char*)path->toLocal8Bit(), ios::in); // on ouvre le fichier en lecture if(map) // si l'ouverture a réussi { while((!map.eof())&&(i<(16*16))) //tant qu'on a pas lu le fichier en entier { x = i/16; //x = l'indice des lignes y = i%16; //y = l'indice des colonnes //cerr<<"i : "<<i<<" - x : "<<x<<" - y :"<<y<<endl; map >> temp; // on lit l'entier if((x<16)&&(y<16)) {elem[x][y]=temp;ref->setChemin(x,y,temp);} //si on est sur la scène mettre l'indice dans elem //(elem sera utilisé dans la seconde partie de la fonction) if (temp==0){ //si 0 -> herb rect = new QGraphicsRectItem(y*35,x*35,35,35); // On construit un rectangle rect->setBrush(herbe); // on le "paint" avec la brush herbe rect->setPen(QPen(Qt::NoPen)); //On efface les bordures ref->setObjectMap(x,y,rect); //on place l'objet dans le répertoire du gestionnaire principal this->addItem(ref->getObjectMap(x,y)); //on affiche l'objet sur la scène ref->setName(x,y,new QString(tr("Terrain de type herbe : \n- constructible"))); } if (temp>10) { if (temp==64) // si 64 -> boue { rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(boue); rect->setPen(QPen(Qt::NoPen)); ref->setName(x,y,new QString(tr("Terrain boueux :\n- inconstructible"))); ref->setObjectMap(x,y,rect); ref->setConstructible(x,y,false); this->addItem(ref->getObjectMap(x,y)); } else if (temp==32) // si 32 -> Panier { rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(panier); rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setName(x,y,new QString(tr("Votre Pic-nic :\nProtegez-le !!"))); ref->setConstructible(x,y,false); ref->setX_fin(x); ref->setY_fin(y); } else // sinon c'est le début { this->ref->setX_deb(x); //Mise à jour des coordonées du début dans le gestionnaire principal this->ref->setY_deb(y); ref->setName(x,y,new QString(tr("Terrain de type sentier : \n- inconstructible"))); elem[x][y]=temp-16; ref->setChemin(x,y,temp-16);//Stockage de la valeur -12 } } i++; //mise à jour de x et y; } //Si on veut faire apparaitre un chemin avec des coudes il est nécessaire de faire la différence par exemple entre un element 6 (= Sud-Ouest) //qui sert de jonction entre un sud et un ouest et un 6 qui sert de jonction entre un est et un sud, car les coudes ne seront pour le même 6 pas les mêmes. //Idee : Parcourir le chemin depuis le début jusqu'au panier en construisant pas à pas le bon élément graphique x=ref->getX_deb(); // on se place au début y=ref->getY_deb(); prev=elem[x][y];// on initialise l'élément "précédent" avec l'élément de départ int ok = 0; // indique si on est arrivé au panier while(!ok) //tant que pas arrivé au panier { switch (elem[x][y]) //on regarde quelle est l'élément à afficher { case 1://si NORD, pas de problème on affiche un nord prev=elem[x][y]; rect = new QGraphicsRectItem(y*35,x*35,35,35);//on cree l'objet rect->setBrush(QBrush(O)); //= brush Ouest, voir les fichiers jpg pour comprendre rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect);//on le referencie ref->setConstructible(x,y,false);//on indique que l'emplacement n'est plus constructible this->addItem(ref->getObjectMap(x,y)); // on l'affiche x--; // on se dirige vers le prochain tronçon de chemin break; case 2://si SUD, pas de problème on affiche un sud prev=elem[x][y]; rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(O); rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); ref->setConstructible(x,y,false); this->addItem(ref->getObjectMap(x,y)); x++; break; case 4://si EST, pas de problème on affiche un sud prev=elem[x][y]; rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(S); rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); ref->setConstructible(x,y,false); this->addItem(ref->getObjectMap(x,y)); y++; break; case 8://si OUEST, pas de problème on affiche un ouest prev=elem[x][y]; rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(S); rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); ref->setConstructible(x,y,false); this->addItem(ref->getObjectMap(x,y)); y--;//ON VA A GAUCHE break; case 5: //si NORD-EST, on ne sait pas si on doit afficher un coude du sud vers est, ou de ouest vers le nord switch(prev) // on regarde donc dans quelle direction on arrive { case 1://SI ON ARRIVE AVEC UNE DIRECTION SUD rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(NO); //ON MET UN COUDE NO = sud vers ouest rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); prev=4; //ET ON REPART AVEC UNE DIRECTION E y++;//ON VA A DROITE break; case 4://SI ON ARRIVE AVEC UNE DIRECTION EST rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(SE); //ON MET UN COUDE SE = ouest vers nord rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); prev=1; //ET ON REPART AVEC UNE DIRECTION S x--;//ON MONTE break; default: break; } break; case 6: //SUD-EST, même systeme switch(prev) { case 2://SI ON ARRIVE AVEC UNE DIRECTION SUD rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(SO); //ON MET UN COUDE SO rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); prev=4; //ET ON REPART AVEC UNE DIRECTION O y++;//ON VA A GAUCHE break; case 4://SI ON ARRIVE AVEC UNE DIRECTION EST rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(NE); //ON MET UN COUDE NE rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); prev=2; //ET ON REPART AVEC UNE DIRECTION SUD x++;//ON DESCEND break; default: break; } break; case 10://SUD-OUEST, même systeme switch(prev) { case 2://SI ON ARRIVE AVEC UNE DIRECTION SUD rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(SE); //ON MET UN COUDE SE rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); prev=8; //ET ON REPART AVEC UNE DIRECTION O y--;//ON VA A DROITE break; case 8://SI ON ARRIVE AVEC UNE DIRECTION EST rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(NO); //ON MET UN COUDE NO rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); prev=2; //ET ON REPART AVEC UNE DIRECTION S x++;//ON DESCEND break; default: break; } break; case 9://NORD-OUEST, même systeme switch(prev) { case 1://SI ON ARRIVE AVEC UNE DIRECTION SUD rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(NE); //ON MET UN COUDE NE rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); prev=8; //ET ON REPART AVEC UNE DIRECTION O y--;//ON VA A GAUCHE break; case 8://SI ON ARRIVE AVEC UNE DIRECTION EST rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(SO); //ON MET UN COUDE SO rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); prev=1; //ET ON REPART AVEC UNE DIRECTION S x--;//ON MONTE break; default: break; } break; default: //SINON = PANIER prev=elem[x][y]; rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(QBrush(O)); rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); ref->setConstructible(x,y,false); rect = new QGraphicsRectItem(y*35,x*35,35,35); rect->setBrush(panier); rect->setPen(QPen(Qt::NoPen)); ref->setObjectMap(x,y,rect); this->addItem(ref->getObjectMap(x,y)); x--; ok=1;//ON EST ARRIVE A LA FIN DU CHEMIN, ON SORT break; } if (ok!=1) { ref->setName(x,y,new QString(tr("Terrain de type sentier :\n- inconstructible"))); } /*1 = chemin vers le Nord 2 = chemin vers le Sud 4 = chemin vers l’Est 8 = chemin vers l’Ouest 5 = chemin vers le NE 6 = chemin vers le SE 9 = chemin vers le NO 10 = chemin vers le SO Une des valeurs précédentes + 16 = case de départ 32 = arrivée des ennemis*/ } map.close(); // on ferme le fichier } else // sinon
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); } }
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(); }
QGraphicsItem* GIFactory::createComponentGI( ComponentDescriptor* type) { qDebug() << "Generating Graphics item for" << type->text(); // collect all the information QString componentName = type->text(); QGraphicsItemGroup* parent = new QGraphicsItemGroup(); // create all the partial items and calculate sizes unsigned int inSection_minWidth = 0; unsigned int outSection_minWidth = 0; unsigned int portSection_lineHeight = 0; QList<PortEntry> inPorts = QList<PortEntry>(); QList<PortEntry> outPorts = QList<PortEntry>(); for (PortDescriptor * port : type->ports()) { PortEntry portEntry = PortEntry(port, parent); unsigned int width = portEntry.textGraphics()->boundingRect().width() + 2 * TEXT_PADDING; unsigned int height = portEntry.textGraphics()->boundingRect().height() + 2 * TEXT_PADDING; // adjust the line height, if needed if (height > portSection_lineHeight) { portSection_lineHeight = height; } switch (port->direction()) { case model::enums::PortDirection::IN : { inPorts.append(portEntry); if (width > inSection_minWidth) { inSection_minWidth = width; } } break; case model::enums::PortDirection::OUT : { outPorts.append(portEntry); if (width > outSection_minWidth) { outSection_minWidth = width; } } break; default: continue; // do not handle other types. } } std::sort(inPorts.begin(), inPorts.end()); std::sort(outPorts.begin(), outPorts.end()); unsigned int portSection_height = inPorts.count() > outPorts.count() ? inPorts.count() * portSection_lineHeight : outPorts.count() * portSection_lineHeight; QGraphicsTextItem* text_compName = new QGraphicsTextItem(componentName, parent); parent->addToGroup(text_compName); unsigned int nameSection_minWidth = text_compName->boundingRect().width() + 2 * TEXT_PADDING; unsigned int nameSection_height = text_compName->boundingRect().height() + 2 * TEXT_PADDING; // adjust the total width unsigned int totalWidth = 0; if (nameSection_minWidth > (inSection_minWidth + outSection_minWidth)) { totalWidth = nameSection_minWidth; if (inSection_minWidth > totalWidth / 2) { // extend outSection_minWidth outSection_minWidth = totalWidth - inSection_minWidth; } else if (outSection_minWidth > totalWidth / 2) { // extend inSection_minWidth inSection_minWidth = totalWidth - outSection_minWidth; } else { // stretch both to totalWidth / 2 inSection_minWidth = totalWidth / 2; outSection_minWidth = totalWidth / 2; } } else { // adjust nameSection_minWidth totalWidth = inSection_minWidth + outSection_minWidth; } // now actually place all the stuff QBrush nameSectionBrush = QBrush(Qt::lightGray, Qt::SolidPattern); QBrush portSectionBrush = QBrush(Qt::white, Qt::SolidPattern); QPen pen = QPen(Qt::black, Qt::SolidLine); QPoint currentPos = QPoint(0, 0); // draw the rectangles QGraphicsRectItem* nameSection = new QGraphicsRectItem( currentPos.x(), currentPos.y(), totalWidth, nameSection_height, parent); nameSection->setBrush(nameSectionBrush); nameSection->setPen(pen); nameSection->setZValue(-1); parent->addToGroup(nameSection); currentPos.ry() += nameSection_height; QGraphicsRectItem* inSection = new QGraphicsRectItem( currentPos.x(), currentPos.y(), inSection_minWidth, portSection_height, parent); inSection->setBrush(portSectionBrush); inSection->setPen(pen); inSection->setZValue(-1); parent->addToGroup(inSection); currentPos.rx() += inSection_minWidth; QGraphicsRectItem* outSection = new QGraphicsRectItem( currentPos.x(), currentPos.y(), outSection_minWidth, portSection_height, parent); outSection->setBrush(portSectionBrush); outSection->setPen(pen); outSection->setZValue(-1); parent->addToGroup(outSection); // place the texts and set the port positions in the port descriptor text_compName->setPos((totalWidth - text_compName->boundingRect().width()) / 2, /*0 + */ TEXT_PADDING); currentPos.setX(0); currentPos.setY(nameSection_height); for(PortEntry inIter : inPorts){ inIter.textGraphics()->setPos(currentPos.x() + TEXT_PADDING, currentPos.y() + TEXT_PADDING); currentPos.ry() += portSection_lineHeight / 2; QPoint portPos = QPoint(currentPos.x() - PORT_DIAMETER, currentPos.y()); inIter.descriptor()->setPosition(portPos); QGraphicsLineItem* lineToPort = new QGraphicsLineItem(QLineF(portPos, currentPos), parent); parent->addToGroup(lineToPort); currentPos.ry() += portSection_lineHeight / 2; } currentPos.setX(totalWidth); currentPos.setY(nameSection_height); for(PortEntry outIter : outPorts){ outIter.textGraphics()->setPos( currentPos.x() - TEXT_PADDING - outIter.textGraphics()->boundingRect().width(), currentPos.y() + TEXT_PADDING); currentPos.ry() += portSection_lineHeight / 2; QPoint portPos = QPoint(currentPos.x() + PORT_DIAMETER, currentPos.y()); outIter.descriptor()->setPosition(portPos); QGraphicsLineItem* lineToPort = new QGraphicsLineItem(QLineF(currentPos, portPos), parent); parent->addToGroup(lineToPort); currentPos.ry() += portSection_lineHeight / 2; } parent->setVisible(true); return parent; }
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.")); }