PDA

View Full Version : How to create Android Style On/Off-Toggle switch in Qt/C++



rawfool
27th March 2013, 11:46
I need to create a toggle switch which resembles android style On/Off-toggle switch in Qt/C++ and not in Qml. Also, I don't want to use radio buttons or QPushButton with toggle properties as it's a bit old style. Can somebody kindly help me in giving the idea for doing the same.
NB: Pls find the sample pic below.
Thank you.

8860

ChiliPalmer
27th March 2013, 20:00
Hi,
I would create a subclass of QAbstractButton.
It pretty much does everything you want. Just make it checkable and reimplement the paintEvent to get the look you would like.

rawfool
28th March 2013, 05:23
Thanks for the reply ChiliPalmer.
Can you kindly show a sample on how to do it. I'm novice in Qt and I've never used QAbstractButton, so if you can ignite me with some basic code, it'll be helpful. Thank you.

ChiliPalmer
28th March 2013, 12:46
Alright, this is very, very basic and won't look that nice. But it might be a good starting point.


AndroidSwitch::AndroidSwitch(QWidget* parent)
: QAbstractButton(parent)
{
setCheckable(true);
}

AndroidSwitch::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
painter.fillRect(rect(), Qt::gray);
QRect switchRect;
QColor switchColor;
QString text;
int halfWidth = width() / 2;
if (isChecked()) {
switchRect = QRect(halfWidth, 0, halfWidth, height());
switchColor = QColor(Qt::cyan);
text = "On";
} else {
switchRect = QRect(0, 0, halfWidth, height());
switchColor = QColor(Qt::darkGray);
text = "Off";
}
painter.fillRect(switchRect, switchColor);
painter.drawText(switchRect, Qt::AlignCenter, text);
}

majstr
29th April 2017, 13:57
Hi
Probably the easiest way is to create checkbox and replace default check image with android style icon