GPT 示例代码

主窗口滑动

#include <QApplication>
#include <QMainWindow>
#include <QPropertyAnimation>

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
        // 设置初始位置为屏幕外(假设窗口宽度为400)
        this->setGeometry(-400, 100, 400, 300);

        // 创建一个属性动画对象
        QPropertyAnimation *animation = new QPropertyAnimation(this, "geometry");
        animation->setDuration(500); // 动画持续时间
        animation->setStartValue(QRect(-400, 100, 400, 300)); // 起始位置(屏幕外)
        animation->setEndValue(QRect(100, 100, 400, 300)); // 最终位置(可视区域)

        // 启动动画
        animation->start();
    }
};

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    MainWindow w;
    w.show(); // 显示主窗口

    return a.exec();
}

#include "main.moc"

子窗口滑动

#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QPropertyAnimation>
#include <QHBoxLayout>
#include <QScreen>

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr)
        : QWidget(parent)
    {
        // 设置主窗口的大小
        setFixedSize(800, 600);
        setWindowTitle("Main Window");

        // 创建一个按钮,用于触发子窗口滑动显示
        QPushButton *button = new QPushButton("Show Sub Window", this);
        button->setGeometry(300, 250, 200, 50);
        connect(button, &QPushButton::clicked, this, &MainWindow::showSubWindow);

        // 创建子窗口,默认为隐藏状态
        subWindow = new QWidget(this);
        subWindow->setFixedSize(300, 600);
        subWindow->setStyleSheet("background-color: lightblue;");

        // 将子窗口定位在屏幕外面(右侧)
        subWindow->move(width(), 0);

        // 创建动画,用来控制子窗口的滑动
        animation = new QPropertyAnimation(subWindow, "pos");
        animation->setDuration(500);  // 设置动画持续时间
    }

private slots:
    void showSubWindow()
    {
        // 设置动画目标位置为 (width() - 300, 0),即主窗口右边位置
        animation->setStartValue(subWindow->pos());
        animation->setEndValue(QPoint(width() - 300, 0));  // 滑动到主窗口右边

        // 启动动画
        animation->start();
    }

private:
    QWidget *subWindow;  // 子窗口
    QPropertyAnimation *animation;  // 动画对象
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

#include "main.moc"