简体   繁体   中英

How to draw a line at angle in QT?

I have a co-ordinate and an angle. Now I want to draw a line from the co-ordinate upto certain length with the specified angle. How can i achieve this?? Can someone give any idea?

Arthur's way of computing the angle is correct, but actually, QT provides built-in methods of drawing lines at specific angles, in particular the functions of the QLineF class in the QLineF header:

#include <QLineF>

void AngleDemo::paintEvent(QPaintEvent *)
{
  QPainter painter(this);

  painter.setPen(QPen(Qt::black,1));

  /* Create the line object: */
  QLineF angleline;

  /* Set the origin: */
  angleline.setP1(QPointF(80,80));

  /* Set the angle and length: */
  angleline.setAngle(45);
  angleline.setLength(50);

  /* Draw the line: */
  painter.drawLine(angleline);
}

From the online documentation of the setAngle() function :

Sets the angle of the line to the given angle (in degrees). This will change the position of the second point of the line such that the line has the given angle.

Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction.

Zero degrees is at the 3 o'clock position.

This function was introduced in Qt 4.4.

assuming your coordinate consists of x and y

double endx = cos(angle)*length;
double endy = sin(angle)*length;

Your line will go from (x,y) to (x+endx, y+endy).

Don't forget your angle needs to be in radians, so if you have it in degrees, such as 0 through 360, convert it like this, and use radians above:

double pi = acos(-1);
double radians = angle / 180.0 * pi;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM