1 Attachment(s)
How to create Android Style On/Off-Toggle switch in Qt/C++
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.
Attachment 8860
Re: How to create Android Style On/Off-Toggle switch in Qt/C++
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.
Re: How to create Android Style On/Off-Toggle switch in Qt/C++
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.
Re: How to create Android Style On/Off-Toggle switch in Qt/C++
Alright, this is very, very basic and won't look that nice. But it might be a good starting point.
Code:
AndroidSwitch
::AndroidSwitch(QWidget* parent
){
setCheckable(true);
}
{
painter.fillRect(rect(), Qt::gray);
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);
}
Re: How to create Android Style On/Off-Toggle switch in Qt/C++
Hi
Probably the easiest way is to create checkbox and replace default check image with android style icon