2011-12-21 23 views
5

Devo ruotare un rettangolo attorno al suo punto centrale e visualizzarlo al centro di un QWidget. Puoi completare questo codice specifico? Se possibile, potresti anche sminuire la spiegazione o fornire un collegamento alla spiegazione più semplice?Ruota il rettangolo attorno al suo centro

Nota: ho letto la documentazione Qt, esempi compilati/demo che trattano della rotazione e I ANCORA non riesco a capirlo!

void Canvas::paintEvent(QPaintEvent *event) 
{ 
    QPainter paint(this); 

    paint.setBrush(Qt::transparent); 
    paint.setPen(Qt::black); 
    paint.drawLine(this->width()/2, 0, this->width()/2, this->height()); 
    paint.drawLine(0, this->height()/2, this->width(), this->height()/2); 

    paint.setBrush(Qt::white); 
    paint.setPen(Qt::blue); 

    // Draw a 13x17 rectangle rotated to 45 degrees around its center-point 
    // in the center of the canvas. 

    paint.drawRect(QRect(0,0, 13, 17)); 

} 

risposta

9
void paintEvent(QPaintEvent* event){ 
    QPainter painter(this); 

    // xc and yc are the center of the widget's rect. 
    qreal xc = width() * 0.5; 
    qreal yc = height() * 0.5; 

    painter.setPen(Qt::black); 

    // draw the cross lines. 
    painter.drawLine(xc, rect().top(), xc, rect().bottom()); 
    painter.drawLine(rect().left(), yc, rect().right(), yc); 

    painter.setBrush(Qt::white); 
    painter.setPen(Qt::blue); 

    // Draw a 13x17 rectangle rotated to 45 degrees around its center-point 
    // in the center of the canvas. 

    // translates the coordinate system by xc and yc 
    painter.translate(xc, yc); 

    // then rotate the coordinate system by 45 degrees 
    painter.rotate(45); 

    // we need to move the rectangle that we draw by rx and ry so it's in the center. 
    qreal rx = -(13 * 0.5); 
    qreal ry = -(17 * 0.5); 
    painter.drawRect(QRect(rx, ry, 13, 17)); 
    } 

Sei in sistema di coordinate del pittore. Quando chiami drawRect (x, y, 13, 17), l'angolo in alto a sinistra è (x,y). Se si desidera che (x, y) sia il centro del rettangolo, è necessario spostare il rettangolo della metà, quindi rx e ry.

È possibile chiamare resetTransform() per reimpostare le trasformazioni effettuate da translate() e rotate().

+3

I * think * Capisco cosa sta succedendo ora. Il pittore SEMPRE parte da 0,0 a prescindere da cosa. Quindi quando traduci a 100.100 Painter inizia ancora a 0,0 ma il nuovo 0,0 ora si trova a 100.100? –

Problemi correlati