/* * Initialize the widget */ MixerCurveWidget::MixerCurveWidget(QWidget *parent) : QGraphicsView(parent) { // Create a layout, add a QGraphicsView and put the SVG inside. // The Mixer Curve widget looks like this: // |--------------------| // | | // | | // | Graph | // | | // | | // | | // |--------------------| setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setRenderHint(QPainter::Antialiasing); curveMin=0.0; curveMax=1.0; QGraphicsScene *scene = new QGraphicsScene(this); QSvgRenderer *renderer = new QSvgRenderer(); plot = new QGraphicsSvgItem(); renderer->load(QString(":/configgadget/images/curve-bg.svg")); plot->setSharedRenderer(renderer); //plot->setElementId("map"); scene->addItem(plot); plot->setZValue(-1); scene->setSceneRect(plot->boundingRect()); setScene(scene); }
bool MainWindow::eventFilter(QObject *target, QEvent *event)// -------- { int var; parsanddrow d; connects u; int dd; if(d.count(openfil())!=0) { dd=d.count(openfil()); d.cord(openfil()); qreal x; qreal y; QGraphicsScene *scene = new QGraphicsScene(ui->graphicsView); scene->setSceneRect(0,0,621,431);//розмір сцені ui->graphicsView->setAlignment(Qt::AlignLeft|Qt::AlignTop ); QDebug qd= qDebug(); if(event->type() == QEvent::MouseButtonDblClick)//опции тут !!!!!!!!!!!!!! { QMouseEvent *mouseEvent =(QMouseEvent*) event; { for(int i=0;i<dd;i++) { x=mouseEvent->pos().x(); y=mouseEvent->pos().y(); if(d.getdev(i)!="con") { if(d.getx(i)>x-30 && d.getx(i)<x+30 && d.gety(i)>y-30 &&d.gety(i)<y+30 ) { if(d.getdev(i)=="modem") { routersetting rout; rout.show(); rout.exec(); } if(d.getdev(i)=="pc") { PCseting pc; pc.show(); pc.exec(); } if(d.getdev(i)=="sw") { Switchseting sw; sw.show(); sw.exec(); } } } } } } if(event->type() == QEvent::MouseButtonPress) { if(d.movstart("graphic.txt")==0) { d.movs("graphic.txt"); } else if(d.movstart("graphic.txt")==4) { QMouseEvent *mouseEvent =(QMouseEvent*) event; { for(int i=0;i<dd;i++) { x=mouseEvent->pos().x(); y=mouseEvent->pos().y(); if(d.getdev(i)!="con") { if(d.getx(i)>x-30 && d.getx(i)<x+30 && d.gety(i)>y-30 &&d.gety(i)<y+30 ) { d.connecting("graphic.txt"); u.begining(d.getmac(i)); drawinwindow(); } } } } } else if(d.movstart("graphic.txt")==5) { QMouseEvent *mouseEvent =(QMouseEvent*) event; { x=mouseEvent->pos().x(); y=mouseEvent->pos().y(); for(int i=0;i<dd;i++) { if(d.getdev(i)!="con") { if(d.getx(i)>x-30 && d.getx(i)<x+30 && d.gety(i)>y-30 &&d.gety(i)<y+30 ) { d.stop("graphic.txt"); u.addconfig(openfil(),d.getmac(i)); //drawinwindow(); } } } } } else if (d.movstart("graphic.txt")==3) { QMouseEvent *mouseEvent =(QMouseEvent*) event; { x=mouseEvent->pos().x(); y=mouseEvent->pos().y(); for(int i=0;i<dd;i++) { if(d.getx(i)>x-30 && d.getx(i)<x+30 && d.gety(i)>y-30 &&d.gety(i)<y+30 ) { if(d.getdev(i)!="con") { d.delate(openfil(),i); drawinwindow(); } } if(d.getdev(i)=="con") { int xpoch; int ypoch; int xend; int yend; for(int jj=0; dd>jj;jj++) { if(d.gatmacconnect1(i)==d.getmac(jj)) { xpoch=d.getx(jj); ypoch=d.gety(jj); } else if(d.gatmacconnect2(i)==d.getmac(jj)) { xend=d.getx(jj); yend=d.gety(jj); } } float dotx=(x-xpoch)/(xend-xpoch); float doty=(y-ypoch)/(yend-ypoch); if(xend>xpoch && x>xpoch && x<xend || xpoch>xend && x<xpoch &&x>xend) if(abs(dotx-doty)==0 && abs(dotx-doty)>=0 ) { d.delate(openfil(),i); drawinwindow(); } } drawinwindow(); } } } else { d.stop("graphic.txt"); } } if(event->type() == QEvent::MouseMove) { qd<<event; qd<<d.movstart("graphic.txt"); QMouseEvent *mouseEvent =(QMouseEvent*) event; { if(d.movstart("graphic.txt")==5) { x=mouseEvent->pos().x(); y=mouseEvent->pos().y(); drawnewconnect(x,y); } if(d.movstart("graphic.txt")==1) { x=mouseEvent->pos().x(); y=mouseEvent->pos().y(); qd<<x<<" "<<y<<" draw"<<"\n"; for(int i=0;i<dd;i++) { if(d.getx(i)>x-30 && d.getx(i)<x+30 && d.gety(i)>y-30 &&d.gety(i)<y+30 ) { qd<<x<<" "<<y<<" cath"<<"\n"; d.rewritedata(openfil(),i,x,y); drawinwindow(); } } } } return true; } d.deletemas(); } return false; }
void MainWindow::drawnewconnect(int xxend, int yyend) { QGraphicsScene *scene = new QGraphicsScene(ui->graphicsView); scene->setSceneRect(0,0,725,575);//розмір сцені ui->graphicsView->setAlignment(Qt::AlignLeft|Qt::AlignTop ); connects u; parsanddrow d; QDebug qd= qDebug(); qApp->applicationDirPath() +"C:/Users/Igro/build-vns_kma-Desktop_Qt_5_1_1_MinGW_32bit-Debug/24.jpeg"; QPixmap pcc; QPixmap modem; QPixmap sw; QPainterPath path; QFont font; font.setPixelSize(50); //pcc.load("C:/Users/Igro/build-vns_kma-Desktop_Qt_5_1_1_MinGW_32bit-Debug/pc.png"); pcc.load("pc.png"); modem.load("modem.png"); sw.load("sw.png"); QString l; //назва приладу int xbeg; int ybeg; int xend; int yend; xend=xxend; yend=yyend; int dd; //кілкість приладів if(d.count(openfil())!=0) { dd=d.count(openfil());//кілкість рядків на 4 властивості отримаємо кілкість приладів d.cord(openfil());//заповнення масивік кординатами та іменами (and mac) for(int i=0;i<dd;i++) { if(d.getmac(i)==u.getbegin()) { xbeg=d.getx(i); ybeg=d.gety(i); } } for(int h=0; h<dd; h++) //малювання { l=d.getdev(h); if(l=="sw") { QGraphicsPixmapItem * a=scene->addPixmap(sw); a->moveBy(d.getx(h),d.gety(h)); QFont font; QPainterPath path; a->setZValue(1); font.setPixelSize(20); font.setBold(false); font.setFamily("Calibri"); path.addText(d.getx(h)-2,d.gety(h)+63,font,d.getname(h)); scene->addPath(path, QPen(QBrush(Qt::black), 1), QBrush(Qt::black)); } if(l=="pc") { QGraphicsPixmapItem * b=scene->addPixmap(pcc); b->moveBy(d.getx(h),d.gety(h)); b->setZValue(1); QFont font; QPainterPath path; font.setPixelSize(20); font.setBold(false); font.setFamily("Calibri"); path.addText(d.getx(h)-2,d.gety(h)+63,font,d.getname(h)); scene->addPath(path, QPen(QBrush(Qt::black), 1), QBrush(Qt::black)); } if(l=="modem") { QGraphicsPixmapItem * bc=scene->addPixmap(modem); bc->moveBy(d.getx(h),d.gety(h)); bc->setZValue(1); QFont font; QPainterPath path; font.setPixelSize(20); font.setBold(false); font.setFamily("Calibri"); path.addText(d.getx(h)-2,d.gety(h)+63,font,d.getname(h)); scene->addPath(path, QPen(QBrush(Qt::black), 1), QBrush(Qt::black)); } if(l=="con") { int xpoch[dd]; int ypoch[dd]; int xend[dd]; int yend[dd]; for(int i=0; dd>i;i++) { if(d.gatmacconnect1(h)==d.getmac(i)) { xpoch[h]=d.getx(i); ypoch[h]=d.gety(i); } else if(d.gatmacconnect2(h)==d.getmac(i)) { xend[h]=d.getx(i); yend[h]=d.gety(i); } } scene->addLine(QLineF(xpoch[h]+15, ypoch[h]+15, xend[h]+15, yend[h]+15), QPen(Qt::blue, 2)); } scene->addLine(QLineF(xbeg+15, ybeg+15, xend, yend), QPen(Qt::blue, 2)); } } ui->graphicsView->setScene(scene); ui->graphicsView->show(); ui->graphicsView->scene()->installEventFilter(this); d.deletemas(); }
PadNavigator::PadNavigator( QWidget *parent) : QGraphicsView(parent) { QSize size(6,2); // Pad item this->pad = new FlippablePad(size); // Selection item RoundRectItem *selectionItem = new RoundRectItem(QRectF(-110, -110, 220, 220), Qt::gray, pad); selectionItem->setZValue(0.5); // Selection animation QPropertyAnimation *smoothXSelection = new QPropertyAnimation(selectionItem, "x"); QPropertyAnimation *smoothYSelection = new QPropertyAnimation(selectionItem, "y"); smoothXSelection->setDuration(100); smoothYSelection->setDuration(100); smoothXSelection->setEasingCurve(QEasingCurve::InCurve); smoothYSelection->setEasingCurve(QEasingCurve::InCurve); // Build the state machine QStateMachine *stateMachine = new QStateMachine(this); QState *frontState = new QState(stateMachine); frontState->assignProperty(pad, "fill", false); frontState->assignProperty(selectionItem, "visible", true); stateMachine->addDefaultAnimation(smoothXSelection); stateMachine->addDefaultAnimation(smoothYSelection); stateMachine->setInitialState(frontState); // 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()); // 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]); RoundRectItem *icon = pad->iconAt(x, y); state->assignProperty(selectionItem, "x", icon->x()); state->assignProperty(selectionItem, "y", icon->y()); } } // Scene QGraphicsScene *scene = new QGraphicsScene(this); scene->setItemIndexMethod(QGraphicsScene::NoIndex); scene->addItem(pad); scene->setSceneRect(scene->itemsBoundingRect()); setScene(scene); // View setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setMinimumSize(50, 50); setCacheMode(CacheBackground); setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing); stateMachine->start(); }
/** Virtual function to setup the UI */ void ConfigGroundVehicleWidget::setupUI(QString frameType) { // Setup the UI Q_ASSERT(m_aircraft); QSvgRenderer *renderer = new QSvgRenderer(); renderer->load(QString(":/configgadget/images/ground-shapes.svg")); m_vehicleImg = new QGraphicsSvgItem(); m_vehicleImg->setSharedRenderer(renderer); UAVDataObject *system = dynamic_cast<UAVDataObject *>(getObjectManager()->getObject(QString("SystemSettings"))); Q_ASSERT(system); QPointer<UAVObjectField> frameTypeSaved = system->getField(QString("AirframeType")); m_aircraft->differentialSteeringSlider1->setEnabled(false); m_aircraft->differentialSteeringSlider2->setEnabled(false); m_aircraft->gvThrottleCurve1GroupBox->setEnabled(true); m_aircraft->gvThrottleCurve2GroupBox->setEnabled(true); m_aircraft->groundVehicleThrottle1->setMixerType(MixerCurve::MIXERCURVE_THROTTLE); m_aircraft->groundVehicleThrottle2->setMixerType(MixerCurve::MIXERCURVE_PITCH); initMixerCurves(frameType); if (frameType == "GroundVehicleDifferential" || frameType == "Differential (tank)") { // Tank m_vehicleImg->setElementId("tank"); setComboCurrentIndex(m_aircraft->groundVehicleType, m_aircraft->groundVehicleType->findText("Differential (tank)")); m_aircraft->gvMotor1ChannelBox->setEnabled(true); m_aircraft->gvMotor2ChannelBox->setEnabled(true); m_aircraft->gvThrottleCurve1GroupBox->setEnabled(false); m_aircraft->gvMotor1Label->setText("Left motor"); m_aircraft->gvMotor2Label->setText("Right motor"); m_aircraft->gvSteering1ChannelBox->setEnabled(false); m_aircraft->gvSteering2ChannelBox->setEnabled(false); m_aircraft->gvSteering1Label->setText("Front steering"); m_aircraft->gvSteering2Label->setText("Rear steering"); m_aircraft->differentialSteeringSlider1->setEnabled(true); m_aircraft->differentialSteeringSlider2->setEnabled(true); m_aircraft->gvThrottleCurve1GroupBox->setTitle("Throttle curve1"); m_aircraft->gvThrottleCurve2GroupBox->setTitle("Throttle curve2 "); m_aircraft->groundVehicleThrottle2->setMixerType(MixerCurve::MIXERCURVE_PITCH); m_aircraft->groundVehicleThrottle1->setMixerType(MixerCurve::MIXERCURVE_THROTTLE); initMixerCurves(frameType); // If new setup, set sliders to defaults and set curves values if (frameTypeSaved->getValue().toString() != "GroundVehicleDifferential") { m_aircraft->differentialSteeringSlider1->setValue(100); m_aircraft->differentialSteeringSlider2->setValue(100); m_aircraft->groundVehicleThrottle1->initLinearCurve(5, 1.0, 0.0); m_aircraft->groundVehicleThrottle2->initLinearCurve(5, 1.0, 0.0); } } else if (frameType == "GroundVehicleMotorcycle" || frameType == "Motorcycle") { // Motorcycle m_vehicleImg->setElementId("motorbike"); setComboCurrentIndex(m_aircraft->groundVehicleType, m_aircraft->groundVehicleType->findText("Motorcycle")); m_aircraft->gvMotor1ChannelBox->setEnabled(true); m_aircraft->gvMotor2ChannelBox->setEnabled(false); m_aircraft->gvMotor2Label->setText("Rear motor"); m_aircraft->gvSteering1ChannelBox->setEnabled(true); m_aircraft->gvSteering2ChannelBox->setEnabled(true); m_aircraft->gvSteering1Label->setText("Front steering"); m_aircraft->gvSteering2Label->setText("Balancing"); // Curve1 for Motorcyle m_aircraft->gvThrottleCurve1GroupBox->setTitle("Throttle curve1"); m_aircraft->gvThrottleCurve1GroupBox->setEnabled(true); m_aircraft->gvThrottleCurve2GroupBox->setTitle("Throttle curve2"); m_aircraft->gvThrottleCurve2GroupBox->setEnabled(true); m_aircraft->groundVehicleThrottle2->setMixerType(MixerCurve::MIXERCURVE_THROTTLE); m_aircraft->groundVehicleThrottle1->setMixerType(MixerCurve::MIXERCURVE_THROTTLE); initMixerCurves(frameType); // If new setup, set curves values if (frameTypeSaved->getValue().toString() != "GroundVehicleMotorCycle") { m_aircraft->groundVehicleThrottle2->initLinearCurve(5, 1.0, 0.0); m_aircraft->groundVehicleThrottle1->initLinearCurve(5, 1.0, 0.0); } } else { // Car m_vehicleImg->setElementId("car"); setComboCurrentIndex(m_aircraft->groundVehicleType, m_aircraft->groundVehicleType->findText("Turnable (car)")); m_aircraft->gvMotor1ChannelBox->setEnabled(true); m_aircraft->gvMotor2ChannelBox->setEnabled(true); m_aircraft->gvMotor1Label->setText("Front motor"); m_aircraft->gvMotor2Label->setText("Rear motor"); m_aircraft->gvSteering1ChannelBox->setEnabled(true); m_aircraft->gvSteering2ChannelBox->setEnabled(true); m_aircraft->gvSteering1Label->setText("Front steering"); m_aircraft->gvSteering2Label->setText("Rear steering"); m_aircraft->gvThrottleCurve2GroupBox->setTitle("Throttle curve2"); m_aircraft->gvThrottleCurve2GroupBox->setEnabled(true); m_aircraft->gvThrottleCurve1GroupBox->setTitle("Throttle curve1"); m_aircraft->gvThrottleCurve1GroupBox->setEnabled(true); m_aircraft->groundVehicleThrottle2->setMixerType(MixerCurve::MIXERCURVE_PITCH); m_aircraft->groundVehicleThrottle1->setMixerType(MixerCurve::MIXERCURVE_THROTTLE); initMixerCurves(frameType); // If new setup, set curves values if (frameTypeSaved->getValue().toString() != "GroundVehicleCar") { m_aircraft->groundVehicleThrottle1->initLinearCurve(5, 1.0, 0.0); m_aircraft->groundVehicleThrottle2->initLinearCurve(5, 1.0, 0.0); } } QGraphicsScene *scene = new QGraphicsScene(); scene->addItem(m_vehicleImg); scene->setSceneRect(m_vehicleImg->boundingRect()); m_aircraft->groundShape->fitInView(m_vehicleImg, Qt::KeepAspectRatio); m_aircraft->groundShape->setScene(scene); }
//! [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] }
//----------------------------------------------------------------------------------------- // 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); } }
void CWinMainView::init() { qDebug() << "#### CWinMainControler::init" << endl; m_tabWidgetCentral = new QTabWidget(); //Pas de parent, setCentralWidget l'attribura à la fenêtre QHBoxLayout* layoutGlobal = new QHBoxLayout(); layoutGlobal->setContentsMargins ( 0, 0, 0, 0 ); layoutGlobal->addWidget(m_tabWidgetCentral); this->setLayout(layoutGlobal); //setCentralWidget(m_tabWidgetCentral); //***HISTOGRAMME QGraphicsScene* scene = new QGraphicsScene(); #if !defined(RES_640_480)// || defined(MULTI_STREAM) scene->setSceneRect(0,0,SCENE_WIDTH, SCENE_HEIGHT); #endif QPen pen(Qt::lightGray, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); QColor color(Qt::lightGray); color.setAlpha(200); QBrush brush(color); for(int i=0; i<SCENE_HEIGHT-1; i=i+10) { scene->addLine(0,i,SCENE_WIDTH-15, i, pen); /*scene->addText(QString::number(i))->setPos(-10,i-5); */ } pen.setColor(Qt::black); scene->addLine(0,SCENE_HEIGHT,SCENE_WIDTH-15, SCENE_HEIGHT, pen); m_lblMesureGraph = new QLabel(" "); scene->addWidget(m_lblMesureGraph)->setPos(0,-20); m_lblConcentrationMax = new QLabel("1000"); m_lblConcentrationMax->setObjectName("lblGraphUnit"); m_lblConcentrationMin = new QLabel("0"); m_lblConcentrationMin->setObjectName("lblGraphUnit"); m_lblConcentrationMoy = new QLabel("500"); m_lblConcentrationMoy->setObjectName("lblGraphUnit"); QLabel* lblInfo = new QLabel(); lblInfo->setObjectName("lblGraphInfo"); scene->addWidget(m_lblConcentrationMax)->setPos(SCENE_WIDTH-23,-10); scene->addWidget(m_lblConcentrationMoy)->setPos(SCENE_WIDTH-13,(SCENE_HEIGHT/2)-10); scene->addWidget(m_lblConcentrationMin)->setPos(SCENE_WIDTH-13,SCENE_HEIGHT-10); QGraphicsProxyWidget* proxyLblInfo= new QGraphicsProxyWidget(); proxyLblInfo->setWidget(lblInfo); //proxyLblInfo = scene->addWidget(lblInfo) proxyLblInfo->resize(100, 60); proxyLblInfo->setPos(SCENE_WIDTH - 140, -20); proxyLblInfo->setVisible(false); int i; for(int j=0; j<m_pModel->getNbStream(); ++j) { QList<CGraphicsRectItem*> list; for(i=0; i<SCENE_WIDTH-20; i=i+10) { if(j==0) { if(i%4==0 || i==0) { scene->addLine(i,SCENE_HEIGHT+3, i,SCENE_HEIGHT-3, pen); m_listGraphicsRectItem.append(new CGraphicsRectItem(i, SCENE_HEIGHT, 20, 0, proxyLblInfo));//, proxyLblMesure)); m_listGraphicsRectItem.last()->setBrush(brush); m_listGraphicsRectItem.last()->setPen(color); scene->addItem(m_listGraphicsRectItem.last()); } else scene->addLine(i,SCENE_HEIGHT, i,SCENE_HEIGHT-3, pen); } if(i%4==0 || i==0) { list.append(new CGraphicsRectItem(i, SCENE_HEIGHT, 20, 0, proxyLblInfo));//, proxyLblMesure)); list.last()->setBrush(brush); list.last()->setPen(color); } } m_listDataGraph.append(list); } scene->addLine(i,SCENE_HEIGHT+3, i,SCENE_HEIGHT-3, pen); pen.setColor(Qt::green); scene->addItem(proxyLblInfo); QGraphicsView* view= new QGraphicsView(scene); QHBoxLayout* graphLayout = new QHBoxLayout(); graphLayout->addWidget(view); graphLayout->setContentsMargins ( 0, 0, 0, 0 ); QWidget* widgetGraph = new QWidget(); widgetGraph->setLayout(graphLayout); //FIN HISTGRAMME qDebug() << "#### CWinMainControler::init 0" << endl; QVBoxLayout* centralLayout = new QVBoxLayout(); for(int i=0; i<m_pModel->getNbStream(); ++i) { QList<QLabel*> listLblMesure; QList<QLabel*> listLblValMesure; qDebug() << "#### CWinMainControler::init 1 " << i <<endl; m_mesureLayout = new QGridLayout(); //Pas de parent, setLayout affect m_groupBoxCentral en parent //m_mesureLayout->setHorizontalSpacing(1); CPushButton* btDetail = new CPushButton(i); btDetail->setObjectName("btDetail"); m_listBtDetail.append(btDetail); QLabel* lblStatusVoie = new QLabel("0000000000"); lblStatusVoie->setObjectName("lblStatusWaterFailure"); m_listLblStatusVoie.append(lblStatusVoie); for(int j=0; j<m_pModel->getNbMeasure(i); ++j) { qDebug() << "#### CWinMainControler::init 2 " << j <<endl; QLabel* lblMesure = new QLabel(QString(" ")+ m_pModel->getMesureValueLbl(i, j)); lblMesure->setObjectName("lblMesure"); listLblMesure.append(lblMesure); QLabel* lblNumVoie = new QLabel(QString("_") +QString::number(i+1)); lblNumVoie->setObjectName("lblMesure"); QLabel* lblValMesure = new QLabel(m_pModel->getMesureValue(i, j) + m_pModel->getMesureValueUnit(i, j)); lblValMesure->setObjectName("lblValMesure"); listLblValMesure.append(lblValMesure); int row = i+j; int col = 0; #ifdef MULTI_MEASURE if(j==0) //Afficher le bouton de détail uniquement pour la première mesure. { m_mesureLayout->addWidget(btDetail,row, col++, Qt::AlignLeft); } else col++; m_mesureLayout->addWidget(lblMesure,row, col++, Qt::AlignLeft);//m_lblValMesure); m_mesureLayout->addWidget(lblValMesure,row, col++, Qt::AlignLeft); #ifdef MULTI_STREAM if(j==0) m_mesureLayout->addWidget(lblStatusVoie,row, col++, Qt::AlignRight); #endif m_mesureLayout->setColumnStretch ( col, 1 ); #else if(j==0) { m_mesureLayout->addWidget(btDetail,row, col++, Qt::AlignLeft); m_mesureLayout->addWidget(lblMesure,row, col++, Qt::AlignLeft);//m_lblValMesure); m_mesureLayout->addWidget(lblValMesure,row, col++, Qt::AlignLeft); #ifdef MULTI_STREAM m_mesureLayout->addWidget(lblStatusVoie,row, col++, Qt::AlignRight); #endif m_mesureLayout->setColumnStretch ( col, 1 ); } #endif #ifdef MAGNESIUM ++j; //ne pas afficher la deuxième mesure #endif } m_listLblValMesure.append(listLblValMesure); m_listLblMesure.append(listLblMesure); centralLayout->addLayout(m_mesureLayout); } //m_lblMesure = new QLabel(tr("MESURE")); //m_lblMesure->setObjectName("lblMesure"); //m_lblValMesure = new QLabel("VAL MESURE"); //m_lblValMesure->setObjectName("lblValMesure"); //m_btDetail = new QPushButton(); //m_btDetail->setObjectName("btDetail"); //QHBoxLayout* mesureLayout = new QHBoxLayout(); //Pas de parent, setLayout affect m_groupBoxCentral en parent //mesureLayout->addWidget(m_btDetail,0, Qt::AlignLeft); //mesureLayout->addWidget(m_lblMesure,0, Qt::AlignLeft);//m_lblValMesure); //mesureLayout->addWidget(m_lblValMesure,50 , Qt::AlignLeft); //info du cycle m_lblStatusAnalyseur = new QLabel("INITIALISATION"); m_lblStatusAnalyseur->setObjectName("lblStatusAnalyseur"); m_lblStatusWaterFailure= new QLabel; m_lblStatusWaterFailure->setObjectName("lblStatusWaterFailure"); m_lblStatusSeuil= new QLabel; m_lblStatusSeuil->setObjectName("lblStatusSeuil"); m_lblCurrentStream = new QLabel; m_lblCurrentStream->setObjectName("lblCurrentStream"); m_lblCurrentStep = new QLabel; m_lblCurrentStep->setObjectName("lblCurrentStep"); m_lblTotalStep = new QLabel; m_lblTotalStep->setObjectName("lblTotalStep"); m_lblNameStep = new QLabel; m_lblNameStep->setObjectName("lblNameStep"); m_lblDateHeure = new QLabel; m_lblDateHeure->setObjectName("lblDateHeure"); QHBoxLayout* horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName("horizontalLayout"); //horizontalLayout->addWidget(m_lblStatusAnalyseur, 40); //40% horizontalLayout->addWidget(m_lblCurrentStream, 30); horizontalLayout->addWidget(m_lblCurrentStep, 15); horizontalLayout->addWidget(m_lblTotalStep, 15); QVBoxLayout* verticalTmpLayout = new QVBoxLayout(); verticalTmpLayout->addStretch(); #if defined(RES_640_480) && defined(MULTI_STREAM) verticalTmpLayout->addWidget(m_lblStatusAnalyseur); #elif defined(RES_640_480) if(m_pModel->getNbStream() < 2) //pour test { verticalTmpLayout->addWidget(m_lblStatusWaterFailure); verticalTmpLayout->addWidget(m_lblStatusSeuil); } verticalTmpLayout->addWidget(m_lblStatusAnalyseur); #else QHBoxLayout* layoutTmpH = new QHBoxLayout(); QVBoxLayout* layoutTmpV = new QVBoxLayout(); layoutTmpV->addWidget(m_lblStatusWaterFailure); layoutTmpV->addWidget(m_lblStatusSeuil); layoutTmpH->addWidget(m_lblStatusAnalyseur); layoutTmpH->addLayout(layoutTmpV); verticalTmpLayout->addLayout(layoutTmpH); #endif verticalTmpLayout->addLayout(horizontalLayout); verticalTmpLayout->addWidget(m_lblNameStep); verticalTmpLayout->addWidget(m_lblDateHeure); //QVBoxLayout* horizontalBottomTmpLayout = new QVBoxLayout(); //horizontalBottomTmpLayout->addWidget(m_lblNameStep); //horizontalBottomTmpLayout->addWidget(m_lblDateHeure); //QVBoxLayout* verticalTmpLayout = new QVBoxLayout(); //verticalTmpLayout->addWidget(m_lblStatusAnalyseur); //verticalTmpLayout->addLayout(horizontalLayout); //verticalTmpLayout->addLayout(horizontalBottomTmpLayout); //Assemblage m_groupBoxCentral et m_groupBoxInfo #if defined(RES_640_480) && !defined(MULTI_STREAM) && !defined(MULTI_MEASURE) centralLayout->addWidget(widgetGraph); #endif centralLayout->addLayout(verticalTmpLayout); //5% //Bouttons de droite m_btAlarm = new QPushButton(); m_btAlarm->setObjectName("btAlarm"); m_btAlarm->setCheckable(true); m_btPlayPause = new QPushButton(); m_btPlayPause->setObjectName("btPlayPause"); m_btStop = new QPushButton(); m_btStop->setObjectName("btStop"); m_btStopEndCycle = new QPushButton(); m_btStopEndCycle->setObjectName("btStopEndCycle"); m_btNext = new QPushButton(); m_btNext->setObjectName("btNext"); QVBoxLayout* verticalLayout = new QVBoxLayout(); verticalLayout->addStretch(); verticalLayout->addWidget(m_btAlarm); verticalLayout->addWidget(m_btPlayPause); verticalLayout->addWidget(m_btStop); verticalLayout->addWidget(m_btStopEndCycle); #if defined(RES_640_480) verticalLayout->addWidget(m_btNext); #endif //Assemblage m_groupBoxRight et centralLayout QHBoxLayout* topLayout = new QHBoxLayout(); topLayout->addLayout(centralLayout, 90); //95% //topLayout->addWidget(m_groupBoxRight, 10); //5% topLayout->addLayout(verticalLayout, 10); //5% QWidget* widgetMain = new QWidget(); widgetMain->setLayout(topLayout); m_tabWidgetCentral->addTab(widgetMain, tr("MESURE")); // m_tabWidgetCentral->setLayout(mainLayout); //*** Page Diagnostique QWidget* widgetDiag = new QWidget(); //Utilisation des boutons pour l'affichage seul (pour ne pas refaire le CSS), ils ne sont pas connectés m_btTemperatureCuve = new QPushButton; m_btTemperatureCuve->setObjectName("btLineEdit"); m_btPressionEau = new QPushButton; m_btPressionEau->setObjectName("btLineEdit"); m_btMesureOptique = new QPushButton; m_btMesureOptique->setObjectName("btLineEdit"); m_btOpticalGain = new QPushButton; m_btOpticalGain->setObjectName("btLineEdit"); m_btOpticalMeasurement = new QPushButton; m_btOpticalMeasurement->setObjectName("btLineEdit"); m_btZeroOpticalMeasurement = new QPushButton; m_btZeroOpticalMeasurement->setObjectName("btLineEdit"); m_btAbsorbanceValue = new QPushButton; m_btAbsorbanceValue->setObjectName("btLineEdit"); QGridLayout* gridLayout = new QGridLayout(); int row =0; gridLayout->addWidget(new QLabel(m_pModel->getOpticalGainLbl()), row,0); gridLayout->addWidget(m_btOpticalGain, row, 1); gridLayout->addWidget(new QLabel(m_pModel->getOpticalGainUnit()), row++,2); #ifndef CYANURE gridLayout->addWidget(new QLabel(m_pModel->getZeroOpticalMeasurementLbl()), row,0); gridLayout->addWidget(m_btZeroOpticalMeasurement, row, 1); gridLayout->addWidget(new QLabel(m_pModel->getZeroOpticalMeasurementUnit()), row++,2); gridLayout->addWidget(new QLabel(m_pModel->getOpticalMeasurementLbl()), row,0); gridLayout->addWidget(m_btOpticalMeasurement, row, 1); gridLayout->addWidget(new QLabel(m_pModel->getOpticalMeasurementUnit()), row++,2); #endif gridLayout->addWidget(new QLabel(m_pModel->getAbsorbanceValueLbl()), row,0); gridLayout->addWidget(m_btAbsorbanceValue, row, 1); gridLayout->addWidget(new QLabel(m_pModel->getAbsorbanceValueUnit()), row++,2); #ifdef SONDE gridLayout->addWidget(new QLabel(tr("Mesure électrode")), row,0); #else gridLayout->addWidget(new QLabel(tr("Mesure optique direct")), row,0); #endif gridLayout->addWidget(m_btMesureOptique, row, 1); gridLayout->addWidget(new QLabel(tr("Pts")), row++,2); #ifndef COULEUR gridLayout->addWidget(new QLabel(tr("Température Cuve")), row,0); gridLayout->addWidget(m_btTemperatureCuve, row, 1); gridLayout->addWidget(new QLabel(tr("°C")), row++,2); #endif gridLayout->addWidget(new QLabel(tr("Capteur de pression d'eau")), row,0); gridLayout->addWidget(m_btPressionEau, row, 1); gridLayout->addWidget(new QLabel(tr("V")), row++,2); m_lblCurrentStreamDiag = new QLabel; m_lblCurrentStreamDiag->setObjectName("lblCurrentStream"); m_lblCurrentStepDiag = new QLabel; m_lblCurrentStepDiag->setObjectName("lblCurrentStep"); m_lblTotalStepDiag = new QLabel; m_lblTotalStepDiag->setObjectName("lblTotalStep"); m_lblNameStepDiag = new QLabel; m_lblNameStepDiag->setObjectName("lblNameStep"); QHBoxLayout* horizontalLayoutDiag = new QHBoxLayout(); horizontalLayoutDiag->setObjectName("horizontalLayout"); horizontalLayoutDiag->addWidget(m_lblCurrentStreamDiag, 30); horizontalLayoutDiag->addWidget(m_lblCurrentStepDiag, 15); horizontalLayoutDiag->addWidget(m_lblTotalStepDiag, 15); QVBoxLayout* verticalLayoutDiag = new QVBoxLayout(); verticalLayoutDiag->addStretch(); verticalLayoutDiag->addLayout(gridLayout); verticalLayoutDiag->addStretch(); #if defined(RES_640_480) verticalLayoutDiag->addLayout(horizontalLayoutDiag); verticalLayoutDiag->addWidget(m_lblNameStepDiag); #endif widgetDiag->setLayout(verticalLayoutDiag); //: Nom de l'onglet à laisser en maj pour toutes les trads m_tabWidgetCentral->addTab(widgetDiag, tr("DIAGNOSTIC")); //***Menu outils //Groupe des boutons //Colonne 1 m_btMaintenance = new QPushButton(); m_btMaintenance->setObjectName("btMaintenance"); QLabel* lblMaintenance = new QLabel(tr("Maintenance")); lblMaintenance->setObjectName("lblOutils"); m_btSequenceur = new QPushButton(); m_btSequenceur->setObjectName("btSequenceur"); QLabel* lblSequenceur = new QLabel(tr("Options")); lblSequenceur->setObjectName("lblOutils"); m_btCopyLogFiles = new QPushButton(); m_btCopyLogFiles->setObjectName("btCopyLogFiles"); QLabel* lblCopyLogFiles = new QLabel(tr("Copie des fichiers log")); lblCopyLogFiles->setObjectName("lblOutils"); /*m_btHelp = new QPushButton(""); m_btHelp->setObjectName("btHelp"); QLabel* lblHelp = new QLabel("Aide"); lblHelp->setObjectName("lblOutils");*/ //Colonne 2 m_btMeasureCard = new QPushButton(); m_btMeasureCard->setObjectName("btMeasureCard"); QLabel* lblMeasureCard = new QLabel(tr("Test électrique")); lblMeasureCard->setObjectName("lblOutils"); /*m_btSave = new QPushButton(""); m_btSave->setObjectName("btSave"); QLabel* lblSave = new QLabel("Sauvegarde"); lblSave->setObjectName("lblOutils"); m_btInformation = new QPushButton(""); m_btInformation->setObjectName("btInformation"); QLabel* lblInformation = new QLabel("Information"); lblInformation->setObjectName("lblOutils");*/ //Colonne 3 /*m_btExternalCard = new QPushButton(); m_btExternalCard->setObjectName("btExternalCard"); QLabel* lblExternalCard = new QLabel(tr("Carte externe")); lblExternalCard->setObjectName("lblOutils");*/ /*m_btParameter = new QPushButton(); m_btParameter->setObjectName("btParameter"); QLabel* lblParameter = new QLabel("Pramètres"); lblParameter->setObjectName("lblOutils"); m_btExplorer = new QPushButton(); m_btExplorer->setObjectName("btExplorer"); QLabel* lblExplorer = new QLabel("Exploreur"); lblExplorer->setObjectName("lblOutils");*/ //Colonne 4 /*m_btEvPump = new QPushButton(); m_btEvPump->setObjectName("btEvPump"); QLabel* lblEvPump = new QLabel(tr("EV/Pompe")); lblEvPump->setObjectName("lblOutils");*/ /*m_btAnalyseur = new QPushButton(); m_btAnalyseur->setObjectName("btAnalyseur"); QLabel* lblAnalyseur = new QLabel("Analyseur"); lblAnalyseur->setObjectName("lblOutils");*/ m_btSwitchConfig = new QPushButton(); connect(m_btSwitchConfig, SIGNAL(clicked()), m_pControler, SLOT(btSwitchConfigPressed())); m_btSwitchConfig->setObjectName("btSwitchConfig"); QLabel* lblSwitchConfig = new QLabel(tr("Switch config")); lblSwitchConfig->setObjectName("lblOutils"); m_btHistorique = new QPushButton(); m_btHistorique->setObjectName("btHistorique"); QLabel* lblHistorique = new QLabel(tr("Historique")); lblHistorique->setObjectName("lblOutils"); QGridLayout *gridLayoutBt = new QGridLayout(); gridLayoutBt->addWidget(m_btMaintenance, 0, 0, Qt::AlignHCenter); gridLayoutBt->addWidget(lblMaintenance, 1, 0, Qt::AlignTop|Qt::AlignHCenter); gridLayoutBt->addWidget(m_btSequenceur, 2, 0, Qt::AlignHCenter); gridLayoutBt->addWidget(lblSequenceur, 3, 0, Qt::AlignTop|Qt::AlignHCenter); #if defined(RES_640_480) //pas de copie de fichier pour le petit panel/ni d'historique gridLayoutBt->addWidget(m_btCopyLogFiles, 4, 0, Qt::AlignHCenter); gridLayoutBt->addWidget(lblCopyLogFiles, 5, 0, Qt::AlignTop|Qt::AlignHCenter); gridLayoutBt->addWidget(m_btHistorique, 2, 3, Qt::AlignHCenter); gridLayoutBt->addWidget(lblHistorique, 3, 3, Qt::AlignTop|Qt::AlignHCenter); #if !defined(RES_640_480) gridLayoutBt->addWidget(m_btSwitchConfig, 4, 3, Qt::AlignHCenter); gridLayoutBt->addWidget(lblSwitchConfig, 5, 3, Qt::AlignTop|Qt::AlignHCenter); #endif #else gridLayoutBt->addWidget(m_btSwitchConfig, 2, 3, Qt::AlignHCenter); gridLayoutBt->addWidget(lblSwitchConfig, 3, 3, Qt::AlignTop|Qt::AlignHCenter); #endif /*gridLayoutBt->addWidget(m_btHelp, 4, 0, Qt::AlignHCenter); gridLayoutBt->addWidget(lblHelp, 5, 0, Qt::AlignTop|Qt::AlignHCenter);*/ gridLayoutBt->addWidget(m_btMeasureCard, 0, 3, Qt::AlignHCenter); gridLayoutBt->addWidget(lblMeasureCard, 1, 3, Qt::AlignTop|Qt::AlignHCenter); /*gridLayoutBt->addWidget(m_btSave, 2, 1, Qt::AlignHCenter); gridLayoutBt->addWidget(lblSave, 3, 1, Qt::AlignTop|Qt::AlignHCenter); gridLayoutBt->addWidget(m_btInformation, 4, 1, Qt::AlignHCenter); gridLayoutBt->addWidget(lblInformation, 5, 1, Qt::AlignTop|Qt::AlignHCenter);*/ /*gridLayoutBt->addWidget(m_btExternalCard, 2, 3, Qt::AlignHCenter); gridLayoutBt->addWidget(lblExternalCard, 3, 3, Qt::AlignTop|Qt::AlignHCenter);*/ /*gridLayoutBt->addWidget(m_btParameter, 2, 2, Qt::AlignHCenter); gridLayoutBt->addWidget(lblParameter, 3, 2, Qt::AlignTop|Qt::AlignHCenter); gridLayoutBt->addWidget(m_btExplorer, 4, 2, Qt::AlignHCenter); gridLayoutBt->addWidget(lblExplorer, 5, 2, Qt::AlignTop|Qt::AlignHCenter);*/ /*gridLayoutBt->addWidget(m_btEvPump, 4, 3, Qt::AlignHCenter); gridLayoutBt->addWidget(lblEvPump, 5, 3, Qt::AlignTop|Qt::AlignHCenter);*/ /*gridLayoutBt->addWidget(m_btAnalyseur, 2, 3, Qt::AlignHCenter); gridLayoutBt->addWidget(lblAnalyseur, 3, 3, Qt::AlignTop|Qt::AlignHCenter);*/ QWidget* widgetMenuTools = new QWidget(); widgetMenuTools->setLayout(gridLayoutBt); m_tabWidgetCentral->addTab(widgetMenuTools, tr("OUTILS")); //*** Onglet HISTOGRAMME m_btNextGraph = new QPushButton(); m_btNextGraph->setObjectName("btNextBig"); m_btPrevGraph = new QPushButton(); m_btPrevGraph->setObjectName("btPrevBig"); m_btPrevGraph->setEnabled(false);; m_lblInfoGraph = new QLabel("INFO GRAPH"); m_lblInfoGraph->setObjectName("lblNameStep"); #if !defined(RES_640_480) || defined(MULTI_STREAM) || defined(MULTI_MEASURE) { QVBoxLayout* layoutMenuGraph = new QVBoxLayout(); layoutMenuGraph->setContentsMargins ( 0, 0, 0, 0 ); layoutMenuGraph->addStretch(); layoutMenuGraph->addWidget(m_btPrevGraph); layoutMenuGraph->addWidget(m_btNextGraph); QVBoxLayout* layoutGraph = new QVBoxLayout(); layoutGraph->addWidget(widgetGraph); #ifdef MULTI_STREAM layoutGraph->addWidget(m_lblInfoGraph); #endif QHBoxLayout* layoutMain = new QHBoxLayout(); layoutMain->addLayout(layoutGraph); #ifdef MULTI_STREAM layoutMain->addLayout(layoutMenuGraph); #endif QWidget* widgetGraphTool = new QWidget(); widgetGraphTool->setLayout(layoutMain); #if !defined(MULTI_MEASURE) && !defined(MULTI_STREAM) #ifndef CERIUM m_tabWidgetCentral->addTab(widgetGraphTool, tr("HISTOGRAMME")); #endif #endif } //**** Onglet des choses en plus pas importante //Groupe des boutons #endif /*m_btSequenceur = new QPushButton(); m_btSequenceur->setObjectName("btSequenceur"); QLabel* lblSequenceur = new QLabel(tr("Séquenceur")); lblSequenceur->setObjectName("lblOutils");*/ m_btSave = new QPushButton(""); m_btSave->setObjectName("btSave"); QLabel* lblSave = new QLabel(tr("Restaurer")); lblSave->setObjectName("lblOutils"); m_btInformation = new QPushButton(""); m_btInformation->setObjectName("btInformation"); QLabel* lblInformation = new QLabel(tr("Information")); lblInformation->setObjectName("lblOutils"); m_btParameter = new QPushButton(); m_btParameter->setObjectName("btParameter"); QLabel* lblParameter = new QLabel(tr("Paramètres")); lblParameter->setObjectName("lblOutils"); m_btExplorer = new QPushButton(); m_btExplorer->setObjectName("btExplorer"); QLabel* lblExplorer = new QLabel(tr("Exploreur")); lblExplorer->setObjectName("lblOutils"); m_btQuit = new QPushButton(); m_btQuit->setObjectName("btExit"); QLabel* lblQuit = new QLabel(tr("Quitter")); lblQuit->setObjectName("lblOutils"); /*m_btAnalyseur = new QPushButton(); m_btAnalyseur->setObjectName("btAnalyseur"); QLabel* lblAnalyseur = new QLabel("Analyseur"); lblAnalyseur->setObjectName("lblOutils");*/ /*m_btHelp = new QPushButton(""); m_btHelp->setObjectName("btHelp"); QLabel* lblHelp = new QLabel("Aide"); lblHelp->setObjectName("lblOutils");*/ QGridLayout *gridLayoutBtPlus = new QGridLayout(); //gridLayoutBtPlus->addWidget(m_btSequenceur, 0, 1, Qt::AlignHCenter); //gridLayoutBtPlus->addWidget(lblSequenceur, 1, 1, Qt::AlignTop|Qt::AlignHCenter); /*gridLayoutBtPlus->addWidget(m_btParameter, 0, 1, Qt::AlignHCenter); gridLayoutBtPlus->addWidget(lblParameter, 1, 1, Qt::AlignTop|Qt::AlignHCenter);*/ gridLayoutBtPlus->addWidget(m_btExplorer, 0, 0, Qt::AlignHCenter); gridLayoutBtPlus->addWidget(lblExplorer, 1, 0, Qt::AlignTop|Qt::AlignHCenter); gridLayoutBtPlus->addWidget(m_btSave, 2, 0, Qt::AlignHCenter); gridLayoutBtPlus->addWidget(lblSave, 3, 0, Qt::AlignTop|Qt::AlignHCenter); gridLayoutBtPlus->addWidget(m_btInformation, 4, 0, Qt::AlignHCenter); gridLayoutBtPlus->addWidget(lblInformation, 5, 0, Qt::AlignTop|Qt::AlignHCenter); gridLayoutBtPlus->addWidget(m_btQuit, 4, 1, Qt::AlignTop|Qt::AlignHCenter); gridLayoutBtPlus->addWidget(lblQuit, 5, 1, Qt::AlignTop|Qt::AlignHCenter); /*gridLayoutBtPlus->addWidget(m_btHelp, 4, 0, Qt::AlignHCenter); gridLayoutBtPlus->addWidget(lblHelp, 5, 0, Qt::AlignTop|Qt::AlignHCenter);*/ /*gridLayoutBtPlus->addWidget(m_btAnalyseur, 2, 3, Qt::AlignHCenter); gridLayoutBtPlus->addWidget(lblAnalyseur, 3, 3, Qt::AlignTop|Qt::AlignHCenter);*/ QWidget* widgetPlus = new QWidget(); widgetPlus->setLayout(gridLayoutBtPlus); m_tabWidgetCentral->addTab(widgetPlus, " + "); setConnexion(); qDebug() << "#### FIN CWinMainControler::CWinMainView" << endl; }
MapWidget::MapWidget() { readMap(); //读取地图信息 zoom=50; int width = map.width(); int height = map.height(); QGraphicsScene *scene = new QGraphicsScene(this); scene->setSceneRect(-width/2,-height/2,width,height); setScene(scene); setCacheMode(CacheBackground); //用于地图缩放的滑动条 QSlider *slider = new QSlider; slider->setOrientation(Qt::Vertical); slider->setRange(1,100); slider->setTickInterval(10); slider->setValue(50); connect(slider,SIGNAL(valueChanged(int)),this,SLOT(slotZoom(int))); QLabel *zoominLabel = new QLabel; zoominLabel->setScaledContents(true); zoominLabel->setPixmap(QPixmap("zoomin.png")); QLabel *zoomoutLabel = new QLabel; zoomoutLabel->setScaledContents(true); zoomoutLabel->setPixmap(QPixmap("zoomout.png")); //坐标值显示区 QLabel *label1 = new QLabel(tr("GraphicsView:")); viewCoord = new QLabel; QLabel *label2 = new QLabel(tr("GraphicsScene:")); sceneCoord = new QLabel; QLabel *label3 = new QLabel(tr("map:")); mapCoord = new QLabel; //坐标显示区布局 QGridLayout *gridLayout = new QGridLayout; gridLayout->addWidget(label1,0,0); gridLayout->addWidget(viewCoord,0,1); gridLayout->addWidget(label2,1,0); gridLayout->addWidget(sceneCoord,1,1); gridLayout->addWidget(label3,2,0); gridLayout->addWidget(mapCoord,2,1); gridLayout->setSizeConstraint(QLayout::SetFixedSize); QFrame *coordFrame = new QFrame; coordFrame->setLayout(gridLayout); //缩放控制子布局 QVBoxLayout *zoomLayout = new QVBoxLayout; zoomLayout->addWidget(zoominLabel); zoomLayout->addWidget(slider); zoomLayout->addWidget(zoomoutLabel); //坐标显示区域布局 QVBoxLayout *coordLayout = new QVBoxLayout; coordLayout->addWidget(coordFrame); coordLayout->addStretch(); //主布局 QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addLayout(zoomLayout); mainLayout->addLayout(coordLayout); mainLayout->addStretch(); mainLayout->setMargin(30); mainLayout->setSpacing(10); setLayout(mainLayout); setWindowTitle("Map Widget"); setMinimumSize(600,400); }
void drawKdenliveTitle( producer_ktitle self, mlt_frame frame, int width, int height, double position, int force_refresh ) { // Obtain the producer mlt_producer producer = &self->parent; mlt_profile profile = mlt_service_profile ( MLT_PRODUCER_SERVICE( producer ) ) ; mlt_properties producer_props = MLT_PRODUCER_PROPERTIES( producer ); // Obtain properties of frame mlt_properties properties = MLT_FRAME_PROPERTIES( frame ); pthread_mutex_lock( &self->mutex ); // Check if user wants us to reload the image if ( mlt_properties_get( producer_props, "_animated" ) != NULL || force_refresh == 1 || width != self->current_width || height != self->current_height || mlt_properties_get( producer_props, "_endrect" ) != NULL ) { //mlt_cache_item_close( self->image_cache ); self->current_image = NULL; mlt_properties_set_data( producer_props, "cached_image", NULL, 0, NULL, NULL ); mlt_properties_set_int( producer_props, "force_reload", 0 ); } if (self->current_image == NULL) { // restore QGraphicsScene QGraphicsScene *scene = static_cast<QGraphicsScene *> (mlt_properties_get_data( producer_props, "qscene", NULL )); if ( force_refresh == 1 && scene ) { scene = NULL; mlt_properties_set_data( producer_props, "qscene", NULL, 0, NULL, NULL ); } if ( scene == NULL ) { int argc = 1; char* argv[1]; argv[0] = (char*) "xxx"; // Warning: all Qt graphic objects (QRect, ...) must be initialized AFTER // the QApplication is created, otherwise their will be NULL if ( app == NULL ) { if ( qApp ) { app = qApp; } else { #ifdef linux if ( getenv("DISPLAY") == 0 ) { mlt_log_panic( MLT_PRODUCER_SERVICE( producer ), "Error, cannot render titles without an X11 environment.\nPlease either run melt from an X session or use a fake X server like xvfb:\nxvfb-run -a melt (...)\n" ); pthread_mutex_unlock( &self->mutex ); return; } #endif app = new QApplication( argc, argv ); const char *localename = mlt_properties_get_lcnumeric( MLT_SERVICE_PROPERTIES( MLT_PRODUCER_SERVICE( producer ) ) ); QLocale::setDefault( QLocale( localename ) ); } qRegisterMetaType<QTextCursor>( "QTextCursor" ); } scene = new QGraphicsScene(); scene->setItemIndexMethod( QGraphicsScene::NoIndex ); scene->setSceneRect(0, 0, mlt_properties_get_int( properties, "width" ), mlt_properties_get_int( properties, "height" )); if ( mlt_properties_get( producer_props, "resource" ) && mlt_properties_get( producer_props, "resource" )[0] != '\0' ) { // The title has a resource property, so we read all properties from the resource. // Do not serialize the xmldata loadFromXml( producer, scene, mlt_properties_get( producer_props, "_xmldata" ), mlt_properties_get( producer_props, "templatetext" ) ); } else { // The title has no resource, all data should be serialized loadFromXml( producer, scene, mlt_properties_get( producer_props, "xmldata" ), mlt_properties_get( producer_props, "templatetext" ) ); } mlt_properties_set_data( producer_props, "qscene", scene, 0, ( mlt_destructor )qscene_delete, NULL ); } QRectF start = stringToRect( QString( mlt_properties_get( producer_props, "_startrect" ) ) ); QRectF end = stringToRect( QString( mlt_properties_get( producer_props, "_endrect" ) ) ); int originalWidth = mlt_properties_get_int( producer_props, "_original_width" ); int originalHeight= mlt_properties_get_int( producer_props, "_original_height" ); const QRectF source( 0, 0, width, height ); if (start.isNull()) { start = QRectF( 0, 0, originalWidth, originalHeight ); } // Effects QList <QGraphicsItem *> items = scene->items(); QGraphicsTextItem *titem = NULL; for (int i = 0; i < items.count(); i++) { titem = static_cast <QGraphicsTextItem*> ( items.at( i ) ); if (titem && !titem->data( 0 ).isNull()) { QStringList params = titem->data( 0 ).toStringList(); if (params.at( 0 ) == "typewriter" ) { // typewriter effect has 2 param values: // the keystroke delay and a start offset, both in frames QStringList values = params.at( 2 ).split( ";" ); int interval = qMax( 0, ( ( int ) position - values.at( 1 ).toInt()) / values.at( 0 ).toInt() ); QTextCursor cursor = titem->textCursor(); cursor.movePosition(QTextCursor::EndOfBlock); // get the font format QTextCharFormat format = cursor.charFormat(); cursor.select(QTextCursor::Document); QString txt = params.at( 1 ).left( interval ); // If the string to insert is empty, insert a space / linebreak so that we don't loose // formatting infos for the next iterations int lines = params.at( 1 ).count( '\n' ); QString empty = " "; for (int i = 0; i < lines; i++) empty.append( "\n " ); cursor.insertText( txt.isEmpty() ? empty : txt, format ); if ( !titem->data( 1 ).isNull() ) titem->setTextWidth( titem->data( 1 ).toDouble() ); } } } //must be extracted from kdenlive title QImage img( width, height, QImage::Format_ARGB32 ); img.fill( 0 ); QPainter p1; p1.begin( &img ); p1.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing ); //| QPainter::SmoothPixmapTransform ); mlt_position anim_out = mlt_properties_get_position( producer_props, "_animation_out" ); if (end.isNull()) { scene->render( &p1, source, start, Qt::IgnoreAspectRatio ); } else if ( position > anim_out ) { scene->render( &p1, source, end, Qt::IgnoreAspectRatio ); } else { double percentage = 0; if ( position && anim_out ) percentage = position / anim_out; QPointF topleft = start.topLeft() + ( end.topLeft() - start.topLeft() ) * percentage; QPointF bottomRight = start.bottomRight() + ( end.bottomRight() - start.bottomRight() ) * percentage; const QRectF r1( topleft, bottomRight ); scene->render( &p1, source, r1, Qt::IgnoreAspectRatio ); if ( profile && !profile->progressive ){ int line=0; double percentage_next_filed = ( position + 0.5 ) / anim_out; QPointF topleft_next_field = start.topLeft() + ( end.topLeft() - start.topLeft() ) * percentage_next_filed; QPointF bottomRight_next_field = start.bottomRight() + ( end.bottomRight() - start.bottomRight() ) * percentage_next_filed; const QRectF r2( topleft_next_field, bottomRight_next_field ); QImage img1( width, height, QImage::Format_ARGB32 ); img1.fill( 0 ); QPainter p2; p2.begin(&img1); p2.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing ); scene->render(&p2,source,r2, Qt::IgnoreAspectRatio ); p2.end(); int next_field_line = ( mlt_properties_get_int( producer_props, "top_field_first" ) ? 1 : 0 ); for (line = next_field_line ;line<height;line+=2){ memcpy(img.scanLine(line),img1.scanLine(line),img.bytesPerLine()); } } } p1.end(); int size = width * height * 4; uint8_t *pointer=img.bits(); QRgb* src = ( QRgb* ) pointer; self->current_image = ( uint8_t * )mlt_pool_alloc( size ); uint8_t *dst = self->current_image; for ( int i = 0; i < width * height * 4; i += 4 ) { *dst++=qRed( *src ); *dst++=qGreen( *src ); *dst++=qBlue( *src ); *dst++=qAlpha( *src ); src++; } mlt_properties_set_data( producer_props, "cached_image", self->current_image, size, mlt_pool_release, NULL ); self->current_width = width; self->current_height = height; } pthread_mutex_unlock( &self->mutex ); mlt_properties_set_int( properties, "width", self->current_width ); mlt_properties_set_int( properties, "height", self->current_height ); }
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(); }
FenPrincipale::FenPrincipale() { // setFixedSize(1200,800); // Dimensions fixées à 850x480px QGridLayout *layout0 = new QGridLayout; // c le layout de base de la page1 QGraphicsScene *scene = new QGraphicsScene; QGraphicsView *vue = new QGraphicsView(scene,this); scene->setSceneRect(0,0,mapLargeur+50,mapHauteur+50); // taille de la scene vue->setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing); vue->setFixedSize(mapLargeur+100,mapHauteur+100); //taille de la vue //Mise en place de la map QPixmap map_im ; map_im.load("map.png"); map=scene->addPixmap(map_im); map->setPos(0,0); map->setZValue(-1); //Rectangle test_debug QRect rectangle1(15,15,618,418); scene->addRect(rectangle1); //rectangle1.moveCenter(QPoint(0,0)); // met le centre au centre //Création de l'origine QRect rectangle(0,0,10,10); rectangle.moveCenter(QPoint(0,0)); // met le centre au centre origine=scene->addRect(rectangle); origine->setPos(map_im.width()/2,map_im.height()/2);// au centre de l'image //Mise en place de du robot QPixmap robot_im ; robot_im.load("petit_robot.png"); robot=scene->addPixmap(robot_im); robot->setZValue(2);// au dessus de l'image carte 2>-1 robot->setOffset(-robot_im.width()/2,-robot_im.height()/2); // origine du robot au centre robot->setPos(origine->x(),origine->y());//placer au centre du palteau //Mise en place de l'obstacle QPen pen(Qt::black, 1, Qt::SolidLine); QBrush brush(Qt::black); //scene.addRect(rectangle, pen, brush); obstacle = scene->addEllipse(0,0,15,15,pen,brush); obstacle->setZValue(1); obstacle->setPos(origine->x(),origine->y()); obstacle2 = scene->addEllipse(0,0,15,15,pen,brush); obstacle2->setZValue(1); obstacle2->setPos(origine->x(),origine->y()); //Ajout au layout principale puis à la fenetre layout0->addWidget(vue, 0,0); setLayout(layout0); //Configuration du Timer pas utiliser (debug) timer = new QTimer(this); // timer->start(1000); //Connection des Signaux/Solts connect( timer, SIGNAL(timeout()), this, SLOT(timerOut()) ); //Pacement par defaut //modifPosition(robot,-750,-1250,90); modifPosition(robot,-750,0,0); testPosObs(obstacle,100,90); }
int main (int argc, char * argv[]) { QApplication app( argc, argv ); // Create QGraphicsScene QGraphicsScene scene; scene.setSceneRect( -600, -250, 1200, 500 ); scene.setItemIndexMethod( QGraphicsScene::NoIndex ); // Draw road scene.addLine( -350, -150, -350, -100 ); scene.addLine( -500, -100, -350, -100 ); scene.addLine( -500, -50, -350, -50 ); scene.addLine( -350, 150, -350, -50 ); scene.addLine( -300, 150, -300, -50 ); scene.addLine( -300, -150, -300, -100 ); scene.addLine( -300, -100, 300, -100 ); scene.addLine( -300, -50, 300, -50 ); scene.addLine( 350, -150, 350, -100 ); scene.addLine( 500, -100, 350, -100 ); scene.addLine( 500, -50, 350, -50 ); scene.addLine( 350, 150, 350, -50 ); scene.addLine( 300, 150, 300, -50 ); scene.addLine( 300, -150, 300, -100 ); scene.addLine( -325, -100, -325, -150 ); scene.addLine( -325, -50, -325, 150 ); scene.addLine( 325, -100, 325, -150 ); scene.addLine( 325, -50, 325, 150 ); scene.addLine( -475, -75, -350, -75 ); scene.addLine( -300, -75, 300, -75 ); scene.addLine( 475, -75, 350, -75 ); // Road notation QGraphicsItem* ptext = scene.addText( "BSN" ); ptext->setPos( -340, -180 ); ptext = scene.addText( "BSS" ); ptext->setPos( -340, 150 ); ptext = scene.addText( "TBN" ); ptext->setPos( 310, -180 ); ptext = scene.addText( "TBS" ); ptext->setPos( 310, 150 ); ptext = scene.addText( "RHW" ); ptext->setPos( -550, -85 ); ptext = scene.addText( "RHE" ); ptext->setPos( 510, -85 ); // Draw traffic lights // Add cars to scene //Car *car = new Car; CarGenerator *pcargen = new CarGenerator( eBSN, -337.5, -150, Qt::blue ); scene.addItem( pcargen ); //car->setStartPos(); // Create QGraphicsView QGraphicsView view( &scene ); view.setViewportUpdateMode( QGraphicsView::BoundingRectViewportUpdate ); view.setWindowTitle( QT_TRANSLATE_NOOP(QGraphicsVIew, "Traffic simulation") ); view.show(); // Set Timer QTimer timer; QObject::connect( &timer, SIGNAL(timeout()), &scene, SLOT(advance()) ); timer.start( 1000/20 ); return app.exec(); }
FxLine::FxLine( QWidget * _parent, FxMixerView * _mv, int _channelIndex ) : QWidget( _parent ), m_mv( _mv ), m_channelIndex( _channelIndex ), m_backgroundActive( Qt::SolidPattern ), m_strokeOuterActive( 0, 0, 0 ), m_strokeOuterInactive( 0, 0, 0 ), m_strokeInnerActive( 0, 0, 0 ), m_strokeInnerInactive( 0, 0, 0 ), m_inRename( false ) { if( !s_sendBgArrow ) { s_sendBgArrow = new QPixmap( embed::getIconPixmap( "send_bg_arrow", 29, 56 ) ); } if( !s_receiveBgArrow ) { s_receiveBgArrow = new QPixmap( embed::getIconPixmap( "receive_bg_arrow", 29, 56 ) ); } setFixedSize( 33, FxLineHeight ); setAttribute( Qt::WA_OpaquePaintEvent, true ); setCursor( QCursor( embed::getIconPixmap( "hand" ), 3, 3 ) ); // mixer sends knob m_sendKnob = new Knob( knobBright_26, this, tr( "Channel send amount" ) ); m_sendKnob->move( 3, 22 ); m_sendKnob->setVisible( false ); // send button indicator m_sendBtn = new SendButtonIndicator( this, this, m_mv ); m_sendBtn->move( 2, 2 ); // channel number m_lcd = new LcdWidget( 2, this ); m_lcd->setValue( m_channelIndex ); m_lcd->move( 4, 58 ); m_lcd->setMarginWidth( 1 ); QString name = Engine::fxMixer()->effectChannel( m_channelIndex )->m_name; setToolTip( name ); m_renameLineEdit = new QLineEdit(); m_renameLineEdit->setText( name ); m_renameLineEdit->setFixedWidth( 65 ); m_renameLineEdit->setFont( pointSizeF( font(), 7.5f ) ); m_renameLineEdit->setReadOnly( true ); m_renameLineEdit->installEventFilter( this ); QGraphicsScene * scene = new QGraphicsScene(); scene->setSceneRect( 0, 0, 33, FxLineHeight ); m_view = new QGraphicsView( this ); m_view->setStyleSheet( "border-style: none; background: transparent;" ); m_view->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); m_view->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); m_view->setAttribute( Qt::WA_TransparentForMouseEvents, true ); m_view->setScene( scene ); QGraphicsProxyWidget * proxyWidget = scene->addWidget( m_renameLineEdit ); proxyWidget->setRotation( -90 ); proxyWidget->setPos( 8, 145 ); connect( m_renameLineEdit, SIGNAL( editingFinished() ), this, SLOT( renameFinished() ) ); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); // Set up the scene QGraphicsScene scene; QRect sceneRect(0,0,740,540); scene.setSceneRect(sceneRect); scene.setItemIndexMethod(QGraphicsScene::NoIndex); Team A(5,QColor(0,0,255)); Team B(5,QColor(255,255,0),50); A.addToScene(scene); B.addToScene(scene); // Set up the view port MyGraphicsView v; v.setRenderHint(QPainter::Antialiasing); v.setCacheMode(QGraphicsView::CacheBackground); v.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); v.setDragMode(QGraphicsView::ScrollHandDrag); v.setScene(&scene); v.show(); // Call circle advance for every time interval of 1000/33 QTimer timer; QObject::connect(&timer, SIGNAL(timeout()), &scene, SLOT(advance())); timer.start(1000 / 33); a.exec(); #ifndef __NO_BOX2D__ B2_NOT_USED(argc); B2_NOT_USED(argv); // Define the ground body. b2BodyDef groundBodyDef[4]; groundBodyDef[0].position.Set(0.0f, 2.7f); //top groundBodyDef[1].position.Set(0.0f, -2.7f); //bottom groundBodyDef[2].position.Set(-3.7f, 0.0f); //left groundBodyDef[3].position.Set(3.7f, 0.0f); //right // Call the body factory which allocates memory for the ground body // from a pool and creates the ground box shape (also from a pool). // The body is also added to the world. b2Body* groundBody[4]; for(unsigned int i = 0; i < 4; i += 1){ groundBody[i] = m_world->CreateBody(&groundBodyDef[i]); } // Define the ground box shape. b2PolygonShape groundBox[4]; // The extents are the half-widths of the box. groundBox[0].SetAsBox(3.7f, 0.003f); groundBox[1].SetAsBox(3.7f, 0.003f); groundBox[2].SetAsBox(0.003f, 2.7f); groundBox[3].SetAsBox(0.003f, 2.7f); // Add the ground fixture to the ground body. for(unsigned int i = 0; i < 4; i += 1){ groundBody[i]->CreateFixture(&groundBox[i], 0.0f); } // Define the dynamic body. We set its position and call the body factory. b2BodyDef bodyDef[6]; for(unsigned int i = 0; i < 6; i += 1){ bodyDef[i].type = b2_dynamicBody; } bodyDef[0].position.Set(1.0f, 2.0f); bodyDef[1].position.Set(1.0f, 0.0f); bodyDef[2].position.Set(1.0f, -2.0f); bodyDef[3].position.Set(2.0f, 1.0f); bodyDef[4].position.Set(2.0f, -1.0f); bodyDef[5].position.Set(3.0f, 0.0f); b2Body* body[6]; for(unsigned int i = 0; i < 6; i += 1){ body[i] = m_world->CreateBody(&bodyDef[i]); b2Vec2 pos = body[i]->GetPosition(); body[i]->SetTransform(pos, 90.0); } // Define another box shape for our dynamic body. b2PolygonShape dynamicBox; dynamicBox.SetAsBox(0.09f, 0.09f); b2Vec2 vertices[19]; vertices[0].Set(-0.090000f, 0.000000f); vertices[1].Set(-0.087385f, -0.021538f); vertices[2].Set(-0.079691f, -0.041825f); vertices[3].Set(-0.067366f, -0.059681f); vertices[4].Set(-0.051126f, -0.074069f); vertices[5].Set(-0.031914f, -0.084151f); vertices[6].Set(-0.010848f, -0.089344f); vertices[7].Set(0.010848f, -0.089344f); vertices[8].Set(0.031914f, -0.084151f); vertices[9].Set(0.051126f, -0.074069f); vertices[10].Set(0.067366f, -0.059681f); vertices[11].Set(0.079691f, -0.041825f); vertices[12].Set(0.087385f, -0.021538f); vertices[13].Set(0.087385f, 0.021538f); vertices[14].Set(0.079691f, 0.041825f); vertices[15].Set(0.067366f, 0.059681f); vertices[16].Set(-0.067366f, 0.059681f); vertices[17].Set(-0.079691f, 0.041825f); vertices[18].Set(-0.087385f, 0.021538f); int32 count = 19; b2PolygonShape polygon; polygon.Set(vertices, count); // Define the dynamic body fixture. b2FixtureDef fixtureDef; b2FixtureDef fixtureDefTri; fixtureDef.shape = &dynamicBox; fixtureDefTri.shape = &polygon; // Set the box density to be non-zero, so it will be dynamic. fixtureDef.density = 1.0f; fixtureDefTri.density = 1.0f; // Override the default friction. fixtureDef.friction = 0.3f; fixtureDefTri.friction = 0.3f; // Add the shape to the body. for(unsigned int i = 0; i < 6; i += 1){ body[i]->CreateFixture(&fixtureDefTri); } // Prepare for simulation. Typically we use a time step of 1/60 of a // second (60Hz) and 10 iterations. This provides a high quality simulation // in most game scenarios. float32 timeStep = 1.0f / 60.0f; int32 velocityIterations = 6; int32 positionIterations = 2; // This is our little game loop. for (int32 i = 0; i < 60; ++i) { // Instruct the world to perform a single step of simulation. // It is generally best to keep the time step and iterations fixed. world.Step(timeStep, velocityIterations, positionIterations); b2Vec2 position[6]; float32 angle[6]; // Now print the position and angle of the body. for(unsigned int i = 0; i < 6; i += 1){ position[i] = body[i]->GetPosition(); angle[i] = body[i]->GetAngle(); } printf("----------------------------------\n"); for(unsigned int i = 0; i < 5; i += 1){ printf("%4.2f %4.2f\n", (position[i].x + 2.7) * 100, 540 - ((position[i].y + 3.7) * 100)); A.setPos(i, (position[i].x + 2.7) * 100, 540 - ((position[i].y + 3.7) * 100)); } printf("----------------------------------\n"); } #endif // When the world destructor is called, all bodies and joints are freed. This can // create orphaned pointers, so be careful about your world management. return 0; }
void FormView::showSetting(Setting setting) { QGraphicsScene *s = scene(); s->clear(); resetTransform(); int scale_fac = 10; int spacing = 20; int planeWidth = setting.get_problem()->get_plane_width()*scale_fac; int planeHeight = setting.get_problem()->get_plane_height()*scale_fac; QRectF bound; for (int i=0; i<setting.get_number_of_planes(); ++i) { int x_offset = i*(planeWidth+spacing)+(spacing/2); int y_offset = (spacing/2); QRectF plane(x_offset,y_offset,planeWidth, planeHeight); s->addRect(plane,QPen(), QBrush(QColor(188, 198, 204),Qt::SolidPattern)); for (int j=0; j<setting.get_plane_at(i)->get_number_of_forms(); ++j) { QPolygonF polygon; Form form; setting.get_plane_at(i)->get_form_at(j, form); vector<Point> points_of_current_form = *(form.get_points()); for (int k=0; k<points_of_current_form.size(); ++k){ Point point = points_of_current_form[k]; polygon.push_back(QPointF(point.get_x()*scale_fac, point.get_y()*scale_fac)); } QGraphicsPolygonItem * polyitem = s->addPolygon(polygon, QPen(QColor(Qt::red)), QBrush(Qt::SolidPattern)); polyitem->setPos(x_offset, y_offset); bound = polygon.boundingRect(); } } float realwidth = container->width() - 50; float width = setting.get_number_of_planes()*(planeWidth+spacing); float realheight = container->height() - 50; float height = planeHeight+spacing; s->setSceneRect(0,0,width,height); float relw = 1; if(width > 0){ relw = realwidth / width; } float relh = 1; if(height > 0){ relh = realheight / height; } float rel = relw; if(relh < relw){ rel = relh; } scale(rel,rel); }
TelemetryMonitorWidget::TelemetryMonitorWidget(QWidget *parent) : QGraphicsView(parent) { setMinimumSize(180,100); setMaximumSize(180,100); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setAlignment(Qt::AlignCenter); setFrameStyle(QFrame::NoFrame); setStyleSheet("background:transparent;"); setAttribute(Qt::WA_TranslucentBackground); setWindowFlags(Qt::FramelessWindowHint); QGraphicsScene *scene = new QGraphicsScene(0,0,180,100, this); QSvgRenderer *renderer = new QSvgRenderer(); if (renderer->load(QString(":/core/images/tx-rx.svg"))) { graph = new QGraphicsSvgItem(); graph->setSharedRenderer(renderer); graph->setElementId("txrxBackground"); QString name; QGraphicsSvgItem* pt; for (int i=0; i<NODE_NUMELEM; i++) { name = QString("tx%0").arg(i); if (renderer->elementExists(name)) { pt = new QGraphicsSvgItem(); pt->setSharedRenderer(renderer); pt->setElementId(name); pt->setParentItem(graph); txNodes.append(pt); } name = QString("rx%0").arg(i); if (renderer->elementExists(name)) { pt = new QGraphicsSvgItem(); pt->setSharedRenderer(renderer); pt->setElementId(name); pt->setParentItem(graph); rxNodes.append(pt); } } scene->addItem(graph); txSpeed = new QGraphicsTextItem(); txSpeed->setDefaultTextColor(Qt::white); txSpeed->setFont(QFont("Helvetica",22,2)); txSpeed->setParentItem(graph); scene->addItem(txSpeed); rxSpeed = new QGraphicsTextItem(); rxSpeed->setDefaultTextColor(Qt::white); rxSpeed->setFont(QFont("Helvetica",22,2)); rxSpeed->setParentItem(graph); scene->addItem(rxSpeed); scene->setSceneRect(graph->boundingRect()); setScene(scene); } connected = false; txValue = 0.0; rxValue = 0.0; setMin(0.0); setMax(1200.0); showTelemetry(); }
ChangeObjectDialog::ChangeObjectDialog(GraphWidget* parent) : QDialog(parent), m_widget(parent), m_nodeImage(NULL) { m_objectsList = new QComboBox(this); m_objectsList->setStyle(QStyleFactory::create("Windows")); connect(m_objectsList, SIGNAL(currentIndexChanged(int)), SLOT(selectObject(int))); m_nameEdit = new QLineEdit(this); m_nameEdit->setMaxLength(MAX_NODE_NAME_LENGTH); connect(m_nameEdit, SIGNAL(textChanged(QString)), this, SLOT(changeNodeName(QString))); connect(this, SIGNAL(enableNodeEdit(bool)), m_nameEdit, SLOT(setEnabled(bool))); QLabel* nameLabel = new QLabel(GRAPH_NODE_NAME_LABEL, this); nameLabel->setBuddy(m_nameEdit); connect(this, SIGNAL(enableNodeEdit(bool)), nameLabel, SLOT(setEnabled(bool))); QLabel* labelImg = new QLabel(GRAPH_NODE_IMAGE_LABEL, this); connect(this, SIGNAL(enableNodeEdit(bool)), labelImg, SLOT(setEnabled(bool))); QGraphicsScene* scene = new QGraphicsScene(this); scene->setItemIndexMethod(QGraphicsScene::NoIndex); scene->setSceneRect(0, 0, IMAGE_PREVIEW_SIZE, IMAGE_PREVIEW_SIZE); m_graphicsView = new QGraphicsView(this); m_graphicsView->setScene(scene); m_graphicsView->setCacheMode(QGraphicsView::CacheBackground); m_graphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); m_graphicsView->setRenderHint(QPainter::Antialiasing); m_graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse); connect(this, SIGNAL(enableNodeEdit(bool)), m_graphicsView, SLOT(setEnabled(bool))); QIntValidator *validator = new QIntValidator(this); validator->setBottom(0); m_weightEdit = new QLineEdit(this); m_weightEdit->setValidator(validator); connect(this, SIGNAL(enableEdgeEdit(bool)), m_weightEdit, SLOT(setEnabled(bool))); connect(m_weightEdit, SIGNAL(textChanged(QString)), this, SLOT(changeNodeName(QString))); QLabel* weightLabel = new QLabel(GRAPH_NODE_WEIGHT_LABEL, this); weightLabel->setBuddy(m_weightEdit); connect(this, SIGNAL(enableEdgeEdit(bool)), weightLabel, SLOT(setEnabled(bool))); QHBoxLayout *nameLayout = new QHBoxLayout; nameLayout->addWidget(nameLabel); nameLayout->addWidget(m_nameEdit); QPushButton* openPictureBtn = new QPushButton(SELECT_PICTURE_LABEL, this); connect(openPictureBtn, SIGNAL(clicked()), SLOT(openPicture())); connect(this, SIGNAL(enableNodeEdit(bool)), openPictureBtn, SLOT(setEnabled(bool))); QHBoxLayout* layoutImg = new QHBoxLayout; layoutImg->addWidget(labelImg); layoutImg->addWidget(openPictureBtn); QHBoxLayout* layoutPower = new QHBoxLayout; layoutPower->addWidget(weightLabel); layoutPower->addWidget(m_weightEdit); QPushButton* confirmButton = new QPushButton(CONFIRM_LABEL, this); connect(confirmButton, SIGNAL(clicked()), SLOT(confirmChanges())); connect(this, SIGNAL(enableConfirmButton(bool)), confirmButton, SLOT(setEnabled(bool))); QPushButton* closeButton = new QPushButton(CANCEL_LABEL, this); closeButton->setDefault(true); connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); QHBoxLayout *layoutBtns = new QHBoxLayout; layoutBtns->addWidget(confirmButton); layoutBtns->addWidget(closeButton); QVBoxLayout* rightLayout = new QVBoxLayout(this); rightLayout->addWidget(m_objectsList); rightLayout->addLayout(nameLayout); rightLayout->addWidget(m_graphicsView); rightLayout->addLayout(layoutImg); rightLayout->addLayout(layoutPower); rightLayout->addLayout(layoutBtns); setWindowTitle(CHANGE_OBJECT_LABEL); updateContent(); }
void dController::printWithTemplate (int RowId) { qDebug()<<Q_FUNC_INFO; //TODO это должно быть в отдельном классе !!! QGraphicsScene * scene = new QGraphicsScene(); bool page_orient= false; int margin_top = MM_TO_POINT(15); int margin_bottom=MM_TO_POINT(15); int margin_left=MM_TO_POINT(35); int margin_right=MM_TO_POINT(15); int page_width=210; int page_height=297; scene->clear(); scene->setSceneRect(0, 0, MM_TO_POINT(page_width),MM_TO_POINT(page_height)); QGraphicsRectItem *border_rect = new QGraphicsRectItem (QRectF(margin_left, margin_top, MM_TO_POINT(page_width)-margin_left-margin_right,MM_TO_POINT(page_height)-margin_top-margin_bottom)); qDebug() <<"margin_rect"<< margin_left << margin_top << margin_left<<margin_right; border_rect->setPen(QPen(Qt::black,2,Qt::DotLine)); border_rect->setBrush(QBrush(Qt::white)); border_rect->setOpacity(0.5); border_rect->setZValue(0); //border_rect->setData(ObjectName, "Border"); scene->addItem(border_rect); SimpleItem* Gritem = new SimpleItem; Gritem->setPos(MM_TO_POINT(180), MM_TO_POINT(0)); Gritem->setPrintFrame(false); Gritem->setText(QStringList()<<QString("Секретно")<<QString("Пункт 12")); Gritem->setFlag(QGraphicsItem::ItemIsMovable); Gritem->setParentItem(border_rect); SimpleItem* MBitem = new SimpleItem; MBitem->setPos(MM_TO_POINT(5), MM_TO_POINT(280)); MBitem->setPrintFrame(false); MBitem->setText(QStringList()<<QString("МБ №-%1"));//.arg(templ)); MBitem->setFlag(QGraphicsItem::ItemIsMovable); scene->addItem(MBitem);//->setParentItem(border_rect); scene->update(); QPrinter printer; QString with_t; with_t.append(spoolDIR).append("compl_teml2.pdf"); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(with_t); printer.setPageSize(QPrinter::A4); QPainter painter(&printer); scene->render(&painter); //QString in_file =mainPDF; //in_file.arg(QString(SID)); qDebug() <<Q_FUNC_INFO<< mainPDF << outPDF; this->mergeTwoPDF(mainPDF,with_t,outPDF); // Рисуем последнюю страничку scene->clear(); border_rect = new QGraphicsRectItem (QRectF(margin_left, margin_top, MM_TO_POINT(page_width)-margin_left-margin_right,MM_TO_POINT(page_height)-margin_top-margin_bottom)); qDebug() <<"margin_rect"<< margin_left << margin_top << margin_left<<margin_right; border_rect->setPen(QPen(Qt::black,2,Qt::DotLine)); border_rect->setBrush(QBrush(Qt::white)); border_rect->setOpacity(0.5); border_rect->setZValue(0); //border_rect->setData(ObjectName, "Border"); scene->addItem(border_rect); SimpleItem* Lastitem = new SimpleItem; Lastitem->setPos(MM_TO_POINT(40), MM_TO_POINT(200)); Lastitem->setPrintFrame(true); Lastitem->setText(QStringList()<<QString("Секретно") <<QString("Пункт 12") <<QString("Исполнитель:ФИО исполнителя") <<QString("Отпечатал:ФИО кто печатал") <<QString("Телефон:2-63-15") <<QString("Инв.№ 12/13") <<QString("Дата: 09.09.09'") <<QString("МБ №-%1"));//.arg(templ) //); Lastitem->setFlag(QGraphicsItem::ItemIsMovable); scene->addItem(Lastitem);//->setParentItem(border_rect); QPrinter printer2; printer2.setOutputFormat(QPrinter::PdfFormat); QString last_p; last_p.append(spoolDIR).append("last_page.pdf"); printer2.setOutputFileName(last_p); printer2.setPageSize(QPrinter::A4); QPainter painter2(&printer2); scene->render(&painter2); // emit sayMeGood(); }
/** Virtual function to setup the UI */ void ConfigFixedWingWidget::setupUI(QString frameType) { Q_ASSERT(m_aircraft); QSvgRenderer *renderer = new QSvgRenderer(); renderer->load(QString(":/configgadget/images/fixedwing-shapes.svg")); planeimg = new QGraphicsSvgItem(); planeimg->setSharedRenderer(renderer); UAVDataObject *system = dynamic_cast<UAVDataObject *>(getObjectManager()->getObject(QString("SystemSettings"))); Q_ASSERT(system); QPointer<UAVObjectField> field = system->getField(QString("AirframeType")); UAVDataObject *mixer = dynamic_cast<UAVDataObject *>(getObjectManager()->getObject(QString("MixerSettings"))); Q_ASSERT(mixer); if (frameType == "FixedWing" || frameType == "Aileron") { planeimg->setElementId("aileron"); setComboCurrentIndex(m_aircraft->fixedWingType, m_aircraft->fixedWingType->findText("Aileron")); m_aircraft->fwRudder1ChannelBox->setEnabled(true); m_aircraft->fwRudder2ChannelBox->setEnabled(true); m_aircraft->fwElevator1ChannelBox->setEnabled(true); m_aircraft->fwElevator2ChannelBox->setEnabled(true); m_aircraft->fwAileron1ChannelBox->setEnabled(true); m_aircraft->fwAileron2ChannelBox->setEnabled(true); m_aircraft->fwAileron1Label->setText("Aileron 1"); m_aircraft->fwAileron2Label->setText("Aileron 2"); m_aircraft->fwElevator1Label->setText("Elevator 1"); m_aircraft->fwElevator2Label->setText("Elevator 2"); m_aircraft->elevonSlider1->setEnabled(false); m_aircraft->elevonSlider2->setEnabled(false); m_aircraft->elevonSlider3->setEnabled(true); m_aircraft->elevonSlider1->setValue(100); m_aircraft->elevonSlider2->setValue(100); // Get values saved if frameType = current frameType set on board if (field->getValue().toString() == "FixedWing") { m_aircraft->elevonSlider3->setValue(getMixerValue(mixer, "RollDifferential")); } else { m_aircraft->elevonSlider3->setValue(0); } } else if (frameType == "FixedWingElevon" || frameType == "Elevon") { planeimg->setElementId("elevon"); setComboCurrentIndex(m_aircraft->fixedWingType, m_aircraft->fixedWingType->findText("Elevon")); m_aircraft->fwAileron1Label->setText("Elevon 1"); m_aircraft->fwAileron2Label->setText("Elevon 2"); m_aircraft->fwElevator1ChannelBox->setEnabled(false); m_aircraft->fwElevator2ChannelBox->setEnabled(false); m_aircraft->fwRudder1ChannelBox->setEnabled(true); m_aircraft->fwElevator1ChannelBox->setCurrentText("None"); m_aircraft->fwRudder2ChannelBox->setEnabled(true); m_aircraft->fwElevator2ChannelBox->setCurrentText("None"); m_aircraft->fwElevator1Label->setText("Elevator 1"); m_aircraft->fwElevator2Label->setText("Elevator 2"); m_aircraft->elevonLabel1->setText("Roll"); m_aircraft->elevonLabel2->setText("Pitch"); m_aircraft->elevonSlider1->setEnabled(true); m_aircraft->elevonSlider2->setEnabled(true); m_aircraft->elevonSlider3->setEnabled(true); // Get values saved if frameType = current frameType set on board if (field->getValue().toString() == "FixedWingElevon") { m_aircraft->elevonSlider1->setValue(getMixerValue(mixer, "MixerValueRoll")); m_aircraft->elevonSlider2->setValue(getMixerValue(mixer, "MixerValuePitch")); m_aircraft->elevonSlider3->setValue(getMixerValue(mixer, "RollDifferential")); } else { m_aircraft->elevonSlider1->setValue(100); m_aircraft->elevonSlider2->setValue(100); m_aircraft->elevonSlider3->setValue(0); } } else if (frameType == "FixedWingVtail" || frameType == "Vtail") { planeimg->setElementId("vtail"); setComboCurrentIndex(m_aircraft->fixedWingType, m_aircraft->fixedWingType->findText("Vtail")); m_aircraft->fwRudder1ChannelBox->setEnabled(false); m_aircraft->fwRudder1ChannelBox->setCurrentText("None"); m_aircraft->fwRudder1ChannelBox->setToolTip(""); m_aircraft->fwRudder2ChannelBox->setEnabled(false); m_aircraft->fwRudder2ChannelBox->setCurrentText("None"); m_aircraft->fwRudder2ChannelBox->setToolTip(""); m_aircraft->fwElevator1Label->setText("Vtail 1"); m_aircraft->fwElevator1ChannelBox->setEnabled(true); m_aircraft->fwElevator2Label->setText("Vtail 2"); m_aircraft->fwElevator2ChannelBox->setEnabled(true); m_aircraft->fwAileron1Label->setText("Aileron 1"); m_aircraft->fwAileron2Label->setText("Aileron 2"); m_aircraft->elevonLabel1->setText("Rudder"); m_aircraft->elevonLabel2->setText("Pitch"); m_aircraft->elevonSlider1->setEnabled(true); m_aircraft->elevonSlider2->setEnabled(true); m_aircraft->elevonSlider3->setEnabled(true); // Get values saved if frameType = current frameType set on board if (field->getValue().toString() == "FixedWingVtail") { m_aircraft->elevonSlider1->setValue(getMixerValue(mixer, "MixerValueYaw")); m_aircraft->elevonSlider2->setValue(getMixerValue(mixer, "MixerValuePitch")); m_aircraft->elevonSlider3->setValue(getMixerValue(mixer, "RollDifferential")); } else { m_aircraft->elevonSlider1->setValue(100); m_aircraft->elevonSlider2->setValue(100); m_aircraft->elevonSlider3->setValue(0); } } QGraphicsScene *scene = new QGraphicsScene(); scene->addItem(planeimg); scene->setSceneRect(planeimg->boundingRect()); m_aircraft->planeShape->fitInView(planeimg, Qt::KeepAspectRatio); m_aircraft->planeShape->setScene(scene); }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); int rowH = 20; listSrcTree.setHorizontalHeaderItem(0, new QStandardItem("Src Devices")); QStandardItem* rootItem = listSrcTree.invisibleRootItem(); QStandardItem* dev1 = new QStandardItem("Device 1"); dev1->setSizeHint(QSize(20, rowH)); dev1->appendRow(new QStandardItem("sensor 0")); dev1->child(dev1->rowCount()-1)->setSizeHint(QSize(20, rowH)); dev1->appendRow(new QStandardItem("sensor 1")); dev1->child(dev1->rowCount()-1)->setSizeHint(QSize(20, rowH)); QStandardItem* dev2 = new QStandardItem("Device 2"); dev2->setSizeHint(QSize(20, rowH)); dev2->appendRow(new QStandardItem("sensor 0")); dev2->child(dev2->rowCount()-1)->setSizeHint(QSize(20, rowH)); dev2->appendRow(new QStandardItem("sensor 1")); dev2->child(dev2->rowCount()-1)->setSizeHint(QSize(20, rowH)); dev2->appendRow(new QStandardItem("sensor 2")); dev2->child(dev2->rowCount()-1)->setSizeHint(QSize(20, rowH)); dev2->appendRow(new QStandardItem("sensor 3")); dev2->child(dev2->rowCount()-1)->setSizeHint(QSize(20, rowH)); rootItem->appendRow(dev1); rootItem->appendRow(dev2); listDstTree.setHorizontalHeaderItem(0, new QStandardItem("Dst Devices")); rootItem = listDstTree.invisibleRootItem(); QStandardItem* dev3 = new QStandardItem("Device 3"); dev3->setSizeHint(QSize(20, rowH)); dev3->appendRow(new QStandardItem("actuator 0")); dev3->child(dev3->rowCount()-1)->setSizeHint(QSize(20, rowH)); dev3->appendRow(new QStandardItem("actuator 1")); dev3->child(dev3->rowCount()-1)->setSizeHint(QSize(20, rowH)); QStandardItem* dev4 = new QStandardItem("Device 4"); dev4->setSizeHint(QSize(20, rowH)); dev4->appendRow(new QStandardItem("actuator 0")); dev4->child(dev4->rowCount()-1)->setSizeHint(QSize(20, rowH)); dev4->appendRow(new QStandardItem("actuator 1")); dev4->child(dev4->rowCount()-1)->setSizeHint(QSize(20, rowH)); dev4->appendRow(new QStandardItem("actuator 2")); dev4->child(dev4->rowCount()-1)->setSizeHint(QSize(20, rowH)); QStandardItem* dev5 = new QStandardItem("Device 5"); dev5->setSizeHint(QSize(20, rowH)); for (int i=0; i<10; ++i) { QString name = "actuator " + QString::number(i); dev5->appendRow(new QStandardItem(name)); dev5->child(dev5->rowCount()-1)->setSizeHint(QSize(20, rowH)); } rootItem->appendRow(dev3); rootItem->appendRow(dev4); rootItem->appendRow(dev5); ui->treeView1->setModel(&listSrcTree); ui->treeView2->setModel(&listDstTree); ui->treeView1->expandAll(); ui->treeView2->expandAll(); // ui->listViewArrows->setModel(&listArrows); //ui->listViewArrows->sizeHintForRow(25); //ui->listViewArrows->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); rootItem = listArrows.invisibleRootItem(); qDebug() << "item size = " << rootItem->sizeHint(); listArrows.setHorizontalHeaderItem(0, new QStandardItem("Mappings")); QStandardItem* item = new QStandardItem("Maps"); //NOTE: tree view header is 17... // hackety hack... item->setSizeHint(QSize(30, 17)); rootItem->appendRow(item); rootItem->appendRow(new QStandardItem("Maps")); rootItem->child(rootItem->rowCount()-1)->setSizeHint(QSize(30, rowH)); rootItem->appendRow(new QStandardItem("Maps")); rootItem->child(rootItem->rowCount()-1)->setSizeHint(QSize(30, rowH)); rootItem->appendRow(new QStandardItem("Maps")); rootItem->child(rootItem->rowCount()-1)->setSizeHint(QSize(30, rowH)); rootItem->appendRow(new QStandardItem("Maps")); rootItem->child(rootItem->rowCount()-1)->setSizeHint(QSize(30, rowH)); rootItem->appendRow(new QStandardItem("Maps")); rootItem->child(rootItem->rowCount()-1)->setSizeHint(QSize(30, rowH)); //try other view //custom view mapperScene = new QMapperDbScene(this); dbModel = new QMapperDbModel(); mapperScene->setMapperDbModel(dbModel); dbModel->LoadFromTest(); //this is another model we might want to overlay on top of existing: dbModelActive = new QMapperDbModel(); dbModelActive->LoadFromTest(1); mapperScene->setMapperDbModelActive(dbModelActive); ui->graphicsView->setScene(mapperScene); ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); mapperScene->updateScene(); qDebug() << "gview rect = " << ui->graphicsView->rect(); //try another view on top // QGraphicsView * view2 = new QGraphicsView(this); // view2->setFrameRect(ui->graphicsView->rect()); // view2->show(); // view2->setBackgroundBrush(QBrush(Qt::blue)); // QMapperDbScene *scene2 = new QMapperDbScene(this); // QMapperDbModel *mod2 = new QMapperDbModel(); // scene2->setMapperDbModel(mod2); // mod2->LoadFromTest(); // view2->setScene(scene2); // scene2->updateScene(); //ui->graphicsView->setMouseTracking(true); //end custom view return; QGraphicsScene *scene = new QGraphicsScene(this); QBrush *brush = new QBrush(Qt::gray); QPen *pen = new QPen(Qt::blue); pen->setWidth(2); //QGraphicsRectItem *rect = scene->addRect(0, 0, 100, 100, *pen, *brush); ui->graphicsView->setScene(scene); //ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); qDebug() << "gview rect = " << ui->graphicsView->rect(); scene->setSceneRect(ui->graphicsView->rect()); float origin_x = 0; float origin_y = 0; CustomRect * crect = new CustomRect(origin_x, origin_y, "dev", "sig"); scene->addItem(crect); }
FxLine::FxLine( QWidget * _parent, FxMixerView * _mv, int _channelIndex ) : QWidget( _parent ), m_mv( _mv ), m_channelIndex( _channelIndex ), m_backgroundActive( Qt::SolidPattern ), m_strokeOuterActive( 0, 0, 0 ), m_strokeOuterInactive( 0, 0, 0 ), m_strokeInnerActive( 0, 0, 0 ), m_strokeInnerInactive( 0, 0, 0 ), m_inRename( false ) { if( !s_sendBgArrow ) { s_sendBgArrow = new QPixmap( embed::getIconPixmap( "send_bg_arrow", 29, 56 ) ); } if( !s_receiveBgArrow ) { s_receiveBgArrow = new QPixmap( embed::getIconPixmap( "receive_bg_arrow", 29, 56 ) ); } setFixedSize( 33, FxLineHeight ); setAttribute( Qt::WA_OpaquePaintEvent, true ); setCursor( QCursor( embed::getIconPixmap( "hand" ), 3, 3 ) ); // mixer sends knob m_sendKnob = new Knob( knobBright_26, this, tr( "Channel send amount" ) ); m_sendKnob->move( 3, 22 ); m_sendKnob->setVisible( false ); // send button indicator m_sendBtn = new SendButtonIndicator( this, this, m_mv ); m_sendBtn->move( 2, 2 ); // channel number m_lcd = new LcdWidget( 2, this ); m_lcd->setValue( m_channelIndex ); m_lcd->move( 4, 58 ); m_lcd->setMarginWidth( 1 ); setWhatsThis( tr( "The FX channel receives input from one or more instrument tracks.\n " "It in turn can be routed to multiple other FX channels. LMMS automatically " "takes care of preventing infinite loops for you and doesn't allow making " "a connection that would result in an infinite loop.\n\n" "In order to route the channel to another channel, select the FX channel " "and click on the \"send\" button on the channel you want to send to. " "The knob under the send button controls the level of signal that is sent " "to the channel.\n\n" "You can remove and move FX channels in the context menu, which is accessed " "by right-clicking the FX channel.\n" ) ); QString name = Engine::fxMixer()->effectChannel( m_channelIndex )->m_name; setToolTip( name ); m_renameLineEdit = new QLineEdit(); m_renameLineEdit->setText( name ); m_renameLineEdit->setFixedWidth( 65 ); m_renameLineEdit->setFont( pointSizeF( font(), 7.5f ) ); m_renameLineEdit->setReadOnly( true ); QGraphicsScene * scene = new QGraphicsScene(); scene->setSceneRect( 0, 0, 33, FxLineHeight ); m_view = new QGraphicsView( this ); m_view->setStyleSheet( "border-style: none; background: transparent;" ); m_view->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); m_view->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); m_view->setAttribute( Qt::WA_TransparentForMouseEvents, true ); m_view->setScene( scene ); QGraphicsProxyWidget * proxyWidget = scene->addWidget( m_renameLineEdit ); proxyWidget->setRotation( -90 ); proxyWidget->setPos( 8, 145 ); connect( m_renameLineEdit, SIGNAL( editingFinished() ), this, SLOT( renameFinished() ) ); }
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; }
void MainWindow::drawinwindow() { parsanddrow d; QGraphicsScene *scene = new QGraphicsScene(ui->graphicsView); scene->setSceneRect(0,0,725,575);//розмір сцені ui->graphicsView->setAlignment(Qt::AlignLeft|Qt::AlignTop ); if(d.count(openfil())!=0) { QPixmap pcc; QPixmap modem; QPixmap sw; QPainterPath path; QFont font; font.setPixelSize(50); //pcc.load("C:/Users/Igro/build-vns_kma-Desktop_Qt_5_1_1_MinGW_32bit-Debug/pc.png"); pcc.load("pc.png"); modem.load("modem.png"); sw.load("sw.png"); QString l; //назва приладу QDebug qd= qDebug(); int dd; //кілкість приладів dd=d.count(openfil());//кілкість рядків на 4 властивості отримаємо кілкість приладів d.cord(openfil());//заповнення масивік кординатами та іменами (and mac) if(dd) for(int h=0; h<dd; h++) //малювання { l=d.getdev(h); if(l=="sw") { QGraphicsPixmapItem * a=scene->addPixmap(sw); a->moveBy(d.getx(h),d.gety(h)); QFont font; QPainterPath path; a->setZValue(1); font.setPixelSize(20); font.setBold(false); font.setFamily("Calibri"); path.addText(d.getx(h)-2,d.gety(h)+63,font,d.getname(h)); scene->addPath(path, QPen(QBrush(Qt::black), 1), QBrush(Qt::black)); } if(l=="pc") { QGraphicsPixmapItem * b=scene->addPixmap(pcc); b->moveBy(d.getx(h),d.gety(h)); b->setZValue(1); QFont font; QPainterPath path; font.setPixelSize(20); font.setBold(false); font.setFamily("Calibri"); path.addText(d.getx(h)-2,d.gety(h)+63,font,d.getname(h)); scene->addPath(path, QPen(QBrush(Qt::black), 1), QBrush(Qt::black)); } if(l=="modem") { QGraphicsPixmapItem * bc=scene->addPixmap(modem); bc->moveBy(d.getx(h),d.gety(h)); bc->setZValue(1); QFont font; QPainterPath path; font.setPixelSize(20); font.setBold(false); font.setFamily("Calibri"); path.addText(d.getx(h)-2,d.gety(h)+63,font,d.getname(h)); scene->addPath(path, QPen(QBrush(Qt::black), 1), QBrush(Qt::black)); } if(l=="con") { int xpoch[dd]; int ypoch[dd]; int xend[dd]; int yend[dd]; bool fir=false; bool sec=false; for(int i=0; dd>i;i++) { if(d.gatmacconnect1(h)==d.getmac(i)) { xpoch[h]=d.getx(i); ypoch[h]=d.gety(i); fir=true; } else if(d.gatmacconnect2(h)==d.getmac(i)) { xend[h]=d.getx(i); yend[h]=d.gety(i); sec=true; } } if(fir==false || sec==false) { d.delate(openfil(),h); } if(fir!=false && sec!=false) scene->addLine(QLineF(xpoch[h]+15, ypoch[h]+15, xend[h]+15, yend[h]+15), QPen(Qt::blue, 2)); } if((l!="modem")|(l!="sw")|(l!="pc")) { qd<<l; } } // d.deletemas(); } else { scene->clear(); } ui->graphicsView->setScene(scene); ui->graphicsView->show(); ui->graphicsView->scene()->installEventFilter(this); }
int main(int argc, char **argv) { QApplication app(argc, argv); QGraphicsScene scene; scene.setSceneRect(0, 0, 800, 480); QSizeF minSize(30, 100); QSizeF prefSize(210, 100); QSizeF maxSize(300, 100); QGraphicsProxyWidget *a = createItem(minSize, prefSize, maxSize, "A"); QGraphicsProxyWidget *b = createItem(minSize, prefSize, maxSize, "B"); QGraphicsProxyWidget *c = createItem(minSize, prefSize, maxSize, "C"); QGraphicsProxyWidget *d = createItem(minSize, prefSize, maxSize, "D"); QGraphicsProxyWidget *e = createItem(minSize, prefSize, maxSize, "E"); QGraphicsProxyWidget *f = createItem(QSizeF(30, 50), QSizeF(150, 50), maxSize, "F (overflow)"); QGraphicsProxyWidget *g = createItem(QSizeF(30, 50), QSizeF(30, 100), maxSize, "G (overflow)"); QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout; l->setSpacing(0); QGraphicsWidget *w = new QGraphicsWidget(0, Qt::Window); w->setPos(20, 20); w->setLayout(l); // vertical QGraphicsAnchor *anchor = l->addAnchor(a, Qt::AnchorTop, l, Qt::AnchorTop); anchor = l->addAnchor(b, Qt::AnchorTop, l, Qt::AnchorTop); anchor = l->addAnchor(c, Qt::AnchorTop, a, Qt::AnchorBottom); anchor = l->addAnchor(c, Qt::AnchorTop, b, Qt::AnchorBottom); anchor = l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop); anchor = l->addAnchor(c, Qt::AnchorBottom, e, Qt::AnchorTop); anchor = l->addAnchor(d, Qt::AnchorBottom, l, Qt::AnchorBottom); anchor = l->addAnchor(e, Qt::AnchorBottom, l, Qt::AnchorBottom); anchor = l->addAnchor(c, Qt::AnchorTop, f, Qt::AnchorTop); anchor = l->addAnchor(c, Qt::AnchorVerticalCenter, f, Qt::AnchorBottom); anchor = l->addAnchor(f, Qt::AnchorBottom, g, Qt::AnchorTop); anchor = l->addAnchor(c, Qt::AnchorBottom, g, Qt::AnchorBottom); // horizontal anchor = l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft); anchor = l->addAnchor(l, Qt::AnchorLeft, d, Qt::AnchorLeft); anchor = l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft); anchor = l->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft); anchor = l->addAnchor(c, Qt::AnchorRight, e, Qt::AnchorLeft); anchor = l->addAnchor(b, Qt::AnchorRight, l, Qt::AnchorRight); anchor = l->addAnchor(e, Qt::AnchorRight, l, Qt::AnchorRight); anchor = l->addAnchor(d, Qt::AnchorRight, e, Qt::AnchorLeft); anchor = l->addAnchor(l, Qt::AnchorLeft, f, Qt::AnchorLeft); anchor = l->addAnchor(l, Qt::AnchorLeft, g, Qt::AnchorLeft); anchor = l->addAnchor(f, Qt::AnchorRight, g, Qt::AnchorRight); scene.addItem(w); scene.setBackgroundBrush(Qt::darkGreen); QGraphicsView *view = new QGraphicsView(&scene); view->show(); return app.exec(); }
Creator::Creator(QApplication &app) { //播放音乐文件 media = new Phonon::MediaObject(); audioOutput = new Phonon::AudioOutput(Phonon::VideoCategory);//声音 Phonon::createPath(media, audioOutput); sourceList.append(QString("music/infinity.wma")); //建立pad pad = new RoundRectItem(QRectF(QPointF(0,0),QPointF(0,0)),QColor(0,0,255,0)); pad->setZValue(0); //设置backwindow backWindow = new QGraphicsProxyWidget(pad); backWidget = new BackWidget(); backWindow->setX(0); backWindow->setY(0); // backWindow->widget()->setWindowOpacity(1); backWindow->setWidget(backWidget); backWindow->setZValue(0); //设置开始窗口按钮 beginWindow = new QGraphicsProxyWidget(pad); beginWidget = new BeginBottum; beginWindow->setWidget(beginWidget); beginWindow->setX(backWindow->x()+400); beginWindow->setY(backWindow->y()+200); beginWindow->widget()->setWindowOpacity(1); beginWindow->setZValue(0.5); //设置音乐按键 musicWindow = new QGraphicsProxyWidget(pad); musicWidget = new ClickBottum; musicWindow->setWidget(musicWidget); musicWindow->setX(backWindow->widget()->width()-120); musicWindow->setY(backWindow->y()+20); musicWindow->widget()->setWindowOpacity(1); musicWindow->setZValue(0.9); //设置AI对战窗口 aiWindow = new QGraphicsProxyWidget(pad); aiWidget = new AIvsAI(); aiWindow->setWidget(aiWidget); aiWindow->setX(backWindow->x()); aiWindow->setY(backWindow->y()); aiWindow->widget()->setWindowOpacity(0); aiWindow->setZValue(0.5); //按钮控件 singleWindow = new QGraphicsProxyWidget(pad); singleWidget = new widgetssingle; singleWindow->setWidget(singleWidget); singleWindow->setX(backWindow->x()+400); singleWindow->setY(backWindow->y()+200); singleWindow->widget()->setWindowOpacity(0); singleWindow->setZValue(0.5); //回放器 replayerWindow = new QGraphicsProxyWidget(pad); replayerWidget = new ReplayWindow(); replayerWindow->setWidget(replayerWidget); replayerWindow->setX(backWindow->x()); replayerWindow->setY(backWindow->y()); replayerWindow->widget()->setWindowOpacity(0); replayerWindow->setZValue(0.5); //地图编辑器 mapEditWindow = new QGraphicsProxyWidget(pad); mapWideget = new MapEditor(); mapEditWindow->setWidget(mapWideget); mapEditWindow->setX(backWindow->x()); mapEditWindow->setY(backWindow->y()); mapEditWindow->widget()->setWindowOpacity(0); mapEditWindow->setZValue(0.5); //人机对战 humanaiWindow = new QGraphicsProxyWidget(pad); humanaiWidget = new humanai(); humanaiWindow->setX(backWindow->x()); humanaiWindow->setY(backWindow->y()); humanaiWindow->setWidget(humanaiWidget); humanaiWindow->widget()->setWindowOpacity(0); humanaiWindow->setZValue(0.5); //制作团队 teamMeneWindow = new QGraphicsProxyWidget(pad); teamMeneWideget = new TeamMenu(); teamMeneWindow->setWidget(teamMeneWideget); teamMeneWindow->setX(backWindow->x()); teamMeneWindow->setY(backWindow->y()); teamMeneWindow->widget()->setWindowOpacity(1); teamMeneWindow->setZValue(0.5); teamWindow = new QGraphicsProxyWidget(pad); teamWideget = new ProductionTeam(); teamWindow->setWidget(teamWideget); teamWindow->widget()->setWindowOpacity(1); teamWindow->setZValue(0.5); teamWideget->setAutoFillBackground(true); QPalette Tpalette = teamWindow->palette(); Tpalette.setBrush(QPalette::Window, QBrush(Qt::black)); teamWindow->setPalette(Tpalette); //登陆 LogInWindow = new QGraphicsProxyWidget(pad); logInwidget = new LogInWidget(); LogInWindow->setWidget(logInwidget); LogInWindow->widget()->setWindowOpacity(0); LogInWindow->setZValue(0.5); LogInWindow->setX(0); LogInWindow->setY(0); //测试赛 TestWindow = new QGraphicsProxyWidget(pad); testwidget = new TestWidget(); TestWindow->setWidget(testwidget); TestWindow->widget()->setWindowOpacity(0); TestWindow->setZValue(0.5); TestWindow->setX(0); TestWindow->setY(0); // beginWindow->close(); aiWindow->close(); singleWindow->close(); replayerWindow->close(); teamMeneWindow->close(); teamWindow->close(); mapEditWindow->close(); humanaiWindow->close(); LogInWindow->close(); TestWindow->close(); QObject::connect(beginWidget->returnUi()->exitmain,SIGNAL(clicked()),this,SLOT(close())); QObject::connect(beginWidget->returnUi()->startsingle,SIGNAL(clicked()),this,SLOT(BeginToSingle())); connect(this->singleWidget->ui->returnpre,SIGNAL(clicked()),this,SLOT(SingleToBegin())); connect(this->singleWidget->ui->aivsai,SIGNAL(clicked()),this,SLOT(SingleToAi())); connect(this->aiWidget->ui->ReturnPre,SIGNAL(clicked()),this,SLOT(AiToSingle())); connect(this->singleWidget->ui->replay,SIGNAL(clicked()),this,SLOT(SingleToReplayer())); connect(this->replayerWidget->returnUi()->pushButton,SIGNAL(clicked()),this,SLOT(ReplayerToSingle())); connect(this->beginWidget->returnUi()->team,SIGNAL(clicked()),this,SLOT(BeginToTeam())); connect(this->teamMeneWideget->returnUi()->pushButton,SIGNAL(clicked()),this,SLOT(TeamToBegin())); connect(this->musicWidget->ui->checkBox,SIGNAL(clicked()),this,SLOT(Music())); connect(this->replayerWidget->returnUi()->pushButton,SIGNAL(clicked()),this->replayerWidget,SLOT(GoInto())); connect(this->mapWideget->returnUi()->pushButton_5,SIGNAL(clicked()),this,SLOT(MapToSingle())); connect(this->singleWidget->ui->mapedit,SIGNAL(clicked()), this, SLOT(SingLeToMap())); connect(this->singleWidget->ui->playervsai,SIGNAL(clicked()),this,SLOT(SingleToHumanai())); connect(this->singleWidget->ui->playervsai, SIGNAL(clicked()), humanaiWidget, SLOT(initEmpty())); connect(this->humanaiWidget->returnUi()->Button_back, SIGNAL(clicked()), this, SLOT(HumanaiToSingle())); connect(this->media,SIGNAL(aboutToFinish()),this,SLOT(continueMusic())); connect(this->singleWidget->ui->levelmode,SIGNAL(clicked()),this,SLOT(SingleToLogIn())); connect(this->logInwidget->returnUi()->pushButton_2,SIGNAL(clicked()),this,SLOT(LogInToSingle())); connect(this->logInwidget,SIGNAL(login_success(QString)),this,SLOT(LogInToTest(QString))); connect(this->testwidget->returnUi()->pushButton,SIGNAL(clicked()),this,SLOT(TestToLogIn())); // connect(this->singleWidget->ui->replay,SIGNAL(clicked()),this->replayerWidget,SLOT(GoInto())); //设置界面背景 QGraphicsScene *scene = new QGraphicsScene(this); scene->addItem(pad); scene->setBackgroundBrush(QBrush(QColor(0,0,0,255))); scene->setSceneRect(scene->itemsBoundingRect()); setScene(scene); showFullScreen(); //建立状态 stateMachine = new QStateMachine(this); MainState = new QState(stateMachine); TeamState = new QState(stateMachine); BeginState = new QState(stateMachine); TestState = new QState(stateMachine); ReplayerState = new QState(stateMachine); WebState = new QState(stateMachine); MapState = new QState(stateMachine); HumanaiState = new QState(stateMachine); ChatState = new QState(stateMachine); WidState = new QState(stateMachine); BeginMenuState= new QState(stateMachine); SingleState= new QState(stateMachine); OldMenuState = new QState(stateMachine); CheckMenuState = new QState(stateMachine); TeamMenuState = new QState(stateMachine); LogState = new QState(stateMachine); MainState->assignProperty(MainState, "z", 0); MainState->assignProperty(beginWindow->widget(), "windowOpacity", 1); stateMachine->setInitialState(MainState); stateMachine->start(); }