How to draw triangle and rhombus shapes using QT

2.3k views Asked by At

I need to draw triangle shape and rhombus shapes like this image.In this code which design triangle shape (figure 1) but I need to add this shape to text "TRI" . And I also need to implement this code to design rhombus shape like (figure 2). please help me to solve this.

Figure 1

void MainWindow::on_btnTri_clicked()
{
    QPen redPen(Qt::black);
    redPen.setWidth(2);
    QRectF rect = QRectF(0, 0, 200, 200);

    QPainterPath path;
    path.moveTo(rect.left() + (rect.width() / 2), rect.top());
    path.lineTo(rect.bottomLeft());
    path.lineTo(rect.bottomRight());
    path.lineTo(rect.left() + (rect.width() / 2), rect.top());
    QGraphicsPathItem* item = ui->graphicsView->scene()->addPath(path, redPen);
    item->setFlag(QGraphicsItem::ItemIsMovable, true);
    item->setFlag(QGraphicsItem::ItemIsSelectable,true);
}

enter image description here

Figure 2 I use this code to design figure 2 But which cannot pass parameters to change there size,My figure 1 designed code I can able pass two parameters to QRectF(0, 0, para1, para2); this for change triangle's size.so I need to change this code to do the same thing using QPainterPath or any other way.

void MainWindow::on_btnRomb_clicked()
{
    QPolygonF romb;
    romb.append(QPointF(20,40));
    romb.append(QPointF(0,20));
    romb.append(QPointF(20,0));
    romb.append(QPointF(40, 20));
    QGraphicsPolygonItem* itemR = ui->graphicsView->scene()->addPolygon(romb);
    itemR->setFlag(QGraphicsItem::ItemIsMovable);
}
1

There are 1 answers

2
eyllanesc On BEST ANSWER

you must use the addText() method of QPainterPath, to place it in the center you must calculate the width and height of the text for it QFontMetrics is used:

QPen redPen(Qt::black);
redPen.setWidth(2);
QRectF rect(0, 0, 200, 200);

QPainterPath path;
path.moveTo(rect.left() + (rect.width() / 2), rect.top());
path.lineTo(rect.bottomLeft());
path.lineTo(rect.bottomRight());
path.lineTo(rect.left() + (rect.width() / 2), rect.top());
path.moveTo(rect.center());

QFont font("Times", 20, QFont::Bold);

QFontMetrics fm(font);
QString text = "TRI";
QSize size = fm.size(Qt::TextSingleLine, text);
path.addText(rect.center()+ QPointF(-size.width()*0.5, size.height()*0.5), font, text);

QGraphicsPathItem *item = ui->graphicsView->scene()->addPath(path, redPen);
item->setFlag(QGraphicsItem::ItemIsMovable, true);
item->setFlag(QGraphicsItem::ItemIsSelectable,true);

For the case of the diamond you should only get the midpoints of each vertex:

QPainterPath path;
QRectF rect(0, 0 , 100, 100);
path.moveTo(rect.center().x(), rect.top());
path.lineTo(rect.right(), rect.center().y());
path.lineTo(rect.center().x(), rect.bottom());
path.lineTo(rect.left(), rect.center().y());
path.lineTo(rect.center().x(), rect.top());
QGraphicsPathItem* itemR = ui->graphicsView->scene()->addPath(path);
itemR->setFlag(QGraphicsItem::ItemIsMovable);