-1

For my project, I wish to have a toggle button. After much research I found this post. toggle-switch-in-qt

I implemented the code of the third post on the link above.

This code works correctly. By cons I do not understand how can we add QLabel for the two states of the toggle button? Would anyone have an idea to do this operation?

Ton van den Heuvel
  • 10,157
  • 6
  • 43
  • 82

1 Answers1

1

You will need to draw the label manually in Switch::paintEvent, depending on isEnabled(), using QPainter::drawText. Since the paint event of the control you refer to is overridden, the default behavior in QAbstractButton::paintEvent which normally draws the button label is not executed.

Ton van den Heuvel
  • 10,157
  • 6
  • 43
  • 82
  • I tried in the PaintEvent method to do p-> drawText (QRect, Qt :: AlignCenter, "name); But there is nothing that appears .... –  Jul 06 '18 at 14:10
  • Are you sure you are not drawing over the text? Is the text drawn at the right coordinates? Try to draw the text *after* drawing the control itself, and draw it at `QRect(margin_, margin_)`. Also make sure you use a color that will be visible by setting the right pen and brush. – Ton van den Heuvel Jul 06 '18 at 15:30
  • Sorry I did not see your message. in isEnabled () I do : QRect rect(0,0,_margin, _margin); QPen penHText(Qt::black); p.setPen(penHText); p.drawText(rect, Qt::AlignHCenter, "myText"); but it does not show anything. Yet even if the coordinates are not correct I should see my text appear ...? –  Jul 10 '18 at 15:16
  • What about: `drawText(QPointF(0, 10), "Some text")`, *after* all the other draw calls? – Ton van den Heuvel Jul 10 '18 at 15:35