QT如何实现左右滑动的按钮
我要实现这样的功能,就想Iphone一样,实现开关按钮,右滑关闭,左滑打开,这样的功能在QT下怎么实现?
望各位大神赐教。
[解决办法]
其实就是2张图片,加2个字符串。
你也可以从QWidget派生自己处理,那样比上面的简单多了。
我帖段代码:
#ifndef SWITCHMENU_H
#define SWITCHMENU_H
#include <QWidget>
class SwitchMenu : public QWidget
{
Q_OBJECT
public:
explicit SwitchMenu(QWidget *parent = 0);
protected:
virtual void paintEvent(QPaintEvent *);
virtual void mousePressEvent(QMouseEvent *);
virtual void mouseReleaseEvent(QMouseEvent *);
signals:
public slots:
public:
void initialize(const QString&, const QString&);
private:
QPixmap m_pixmapBk;
QPixmap m_pixmapFore;
bool m_bOn;
bool m_bLBtnDown;
};
#endif // SWITCHMENU_H
#include "switchmenu.h"
#include <QPainter>
#include <QMouseEvent>
SwitchMenu::SwitchMenu(QWidget *parent) :
QWidget(parent)
{
setWindowFlags(Qt::FramelessWindowHint);
m_bOn = false;
m_bLBtnDown = false;
}
void SwitchMenu::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.drawPixmap(QPoint(0,0), m_pixmapBk);
QPoint ptFore;
if (m_bOn) {
ptFore = rect().topLeft();
} else {
ptFore = QPoint(this->width() - m_pixmapFore.width(),
this->rect().top());
}
painter.drawPixmap(ptFore, m_pixmapFore);
QRect rcOn;
rcOn.setTopLeft(rect().topLeft());
rcOn.setBottomRight(QPoint(m_pixmapFore.width(), m_pixmapFore.height()));
painter.drawText(rcOn, Qt::AlignCenter, "ON");
QRect rcOff;
rcOff.setTopLeft(QPoint(rect().width() - m_pixmapFore.width(), rect().top()));
rcOff.setBottomRight(rect().bottomRight());
painter.drawText(rcOff, Qt::AlignCenter, "Off");
}
void SwitchMenu::mousePressEvent(QMouseEvent *)
{
m_bLBtnDown = true;
}
void SwitchMenu::mouseReleaseEvent(QMouseEvent *e)
{
if (m_bLBtnDown) {
m_bOn = !m_bOn;
m_bLBtnDown = false;
}
update();
}
void SwitchMenu::initialize(const QString& strImageBk, const QString& strImageFore)
{
m_pixmapBk.load(strImageBk);
m_pixmapFore.load(strImageFore);
int nWidth = m_pixmapBk.width();
int nHeight = m_pixmapBk.height();
setGeometry(0, 0, m_pixmapBk.width(), m_pixmapBk.height());
}
SwitchMenu switchMenu;
switchMenu.initialize(":/res/switchMenu_bk", ":/res/switchMenu_fore");
switchMenu.show();