Qt纯用代码写一个左右滑动开关按钮,添加到界面
时间: 2024-01-15 07:03:39 浏览: 206
好的,我可以为你提供一个基于Qt代码的左右滑动开关按钮的实现方法。
首先,我们需要在Qt的工程中添加一个自定义控件类。创建一个名为`SlideSwitch`的类,继承自`QWidget`,并在`.h`文件中添加以下代码:
```
class SlideSwitch : public QWidget
{
Q_OBJECT
public:
explicit SlideSwitch(QWidget *parent = nullptr);
void setSwitchColor(const QColor &color);
protected:
void paintEvent(QPaintEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
private:
QColor m_switchColor;
bool m_isOn;
QPoint m_dragPos;
};
```
然后,在`.cpp`文件中实现这些函数:
```
SlideSwitch::SlideSwitch(QWidget *parent) : QWidget(parent)
{
setFixedSize(60, 30);
m_switchColor = QColor(0, 150, 136);
m_isOn = false;
}
void SlideSwitch::setSwitchColor(const QColor &color)
{
m_switchColor = color;
update();
}
void SlideSwitch::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QRectF bgRect(0, 0, width(), height());
QRectF switchRect(0, 0, height(), height());
switchRect.moveLeft(m_isOn ? width() - height() : 0);
QBrush bgBrush(QColor(220, 220, 220));
painter.setBrush(bgBrush);
painter.setPen(Qt::NoPen);
painter.drawRoundedRect(bgRect, height() / 2, height() / 2);
QBrush switchBrush(m_switchColor);
painter.setBrush(switchBrush);
painter.drawEllipse(switchRect);
QWidget::paintEvent(event);
}
void SlideSwitch::mousePressEvent(QMouseEvent *event)
{
m_dragPos = event->pos();
}
void SlideSwitch::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
int distance = event->pos().x() - m_dragPos.x();
if (m_isOn) {
if (distance < 0) {
m_isOn = false;
update();
}
} else {
if (distance > 0) {
m_isOn = true;
update();
}
}
}
}
void SlideSwitch::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
int distance = event->pos().x() - m_dragPos.x();
if (m_isOn) {
if (distance < 0) {
m_isOn = false;
update();
}
} else {
if (distance > 0) {
m_isOn = true;
update();
}
}
}
}
```
最后,在你的界面中使用这个自定义控件:
```
SlideSwitch *switchButton = new SlideSwitch(this);
switchButton->setGeometry(10, 10, 60, 30);
```
这样就完成了一个左右滑动开关按钮的实现啦!
阅读全文