2011-12-21 14 views
5

Necesito rotar un rectángulo alrededor de su punto central y mostrarlo en el centro de un QWidget. ¿Puedes completar este código específico? Si es posible, ¿podría simplificar la explicación o proporcionar un enlace a la explicación más simple?Gire el rectángulo alrededor de su centro

Nota: He leído la documentación de Qt, ejemplos/demostraciones compilados que tratan sobre la rotación y ¡TODAVÍA no puedo entenderlo!

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)); 

} 

Respuesta

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)); 
    } 

está dentro del sistema de coordenadas del pintor. Cuando llama a drawRect (x, y, 13, 17), su esquina superior izquierda está en (x,y). Si quiere que (x, y) sea el centro de su rectángulo, entonces necesita mover el rectángulo a la mitad, de ahí rx y ry.

Puede llamar al resetTransform() para restablecer las transformaciones realizadas por translate() y rotate().

+3

I * think * Entiendo lo que está sucediendo ahora. El pintor SIEMPRE comienza en 0,0 sin importar qué. ¿Entonces cuando traduces a 100,100 Painter aún comienza en 0,0 pero el nuevo 0,0 ahora es 100,100? –

Cuestiones relacionadas