以下是一个使用Qt实现旋转开关的示例代码:
mainwindow.h文件:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPropertyAnimation>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_switchButton_clicked();
private:
Ui::MainWindow *ui;
QPropertyAnimation *animation;
};
#endif // MAINWINDOW_H
mainwindow.cpp文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 创建动画对象
animation = new QPropertyAnimation(ui->switchButton, "angle", this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_switchButton_clicked()
{
if (animation->state() == QAbstractAnimation::Running) {
return;
}
if (ui->switchButton->isChecked()) {
animation->setStartValue(0);
animation->setEndValue(90);
animation->setDuration(500);
animation->start();
} else {
animation->setStartValue(90);
animation->setEndValue(0);
animation->setDuration(500);
animation->start();
}
}
在Qt Designer中,创建一个窗口,并将一个QPushButton控件添加到该窗口。然后,为该按钮设置两个图标:打开和关闭状态下的图标。接下来,使用“属性编辑器”将该按钮的“checkable”属性设置为true。
最后,在主函数中创建一个MainWindow对象并显示它:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
运行程序,单击按钮即可看到旋转开关的效果。