Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    Not able to center text veritical using painter.

    General and Desktop
    1
    1
    2083
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • J
      justdad last edited by

      I am using QPainter to paint a custom background on a widget. Then I want to center some text on this widget. Looking through the threads, if I want to use HTML type of text to paint in top of this, I need to use a QTextDocument. In doing this I can center the text horizontally but the text is always painted at the top of the bounding rectangle. I have tried using the Vertical Alighn flag but it does not help. How do I get the text below to alighn veritcally?

      Ken

      @void ButtonWidget::paintEvent(QPaintEvent *)
      {
      QPainter painter(this);
      int Radius=40;

      painter.setRenderHint(QPainter::Antialiasing, antialiased);
      
      QRect r1 = this->rect();
      
      QPen myPen;
      
      
      QPainterPath myPath;
      QRectF fboundingRect;
      
      QPoint StartPoint = QPoint(0,0);
      
      myPath.moveTo(StartPoint);
      
      // Draw upper right curve
      fboundingRect = QRectF(r1.width()-Radius,0,Radius-1,Radius-1);
      
      myPath.arcTo(fboundingRect, 90, -90);
      myPath.lineTo(r1.width()-1,r1.height()-Radius/2);
      
      // Draw Lower Right curver
      fboundingRect = QRectF(r1.width()-Radius,r1.height()-Radius,Radius-1,Radius-1);
      myPath.arcTo(fboundingRect, 0, -90);
      
      myPath.lineTo(0,r1.height());
      
      //Close the polygon
      myPath.lineTo(0,0);
      
      myPen.setColor(LineColor);
      painter.setBrush(FillColor);
      painter.setPen(myPen);
      painter.drawPath(myPath);
      
      if (DisplayMode==0)
      {
          painter.setPen(TextColor);
          painter.setFont(QFont("Arial", 30));
          painter.drawText(this->rect(),Qt::AlignCenter,DisplayText);
      
      } else
      {
      
          QTextDocument *doc = new QTextDocument(this);
          doc->setUndoRedoEnabled(false);
                 
          doc->setHtml("<font size=14 color=\"white\"><b>"+DisplayText+"</b><br></font><font size=20>"+MinorText+"</font>" );
      
          doc->setTextWidth(width());
      
          doc->setUseDesignMetrics(true);
          doc->setDefaultTextOption ( QTextOption (Qt::AlignVCenter )  );
          painter.setRenderHint(QPainter::Antialiasing, true);
      
          doc->drawContents(&painter);
          delete doc;
      
      
      
      }
      

      }@

      1 Reply Last reply Reply Quote 0
      • First post
        Last post