QT开发中文网

用Qt做一个旋转的开关

以下是一个使用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();
}

运行程序,单击按钮即可看到旋转开关的效果。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=2120

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?