0

好吧,有什么方法可以让这个程序在每次单击按钮时随机更改变量 x 和 y 我是编程新手...

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QtGUI>
#include <QWidget>
#include <cstdlib>
#include <ctime>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);


    QWidget *window = new QWidget;

    srand(time(0));
    int x = 1+(rand()%900);
    int y = 1+(rand()%400);

    QPushButton *MainInter = new QPushButton("Push me!",window);

    QPropertyAnimation *animation = new QPropertyAnimation(MainInter, "pos");
    animation->setDuration(0);
    animation->setEndValue(QPoint(x,y));

    Object::connect(MainInter,SIGNAL(released()),animation,SLOT(start()));


    window->resize(900,500);
    window->show();

    return a.exec();
}  
4

1 回答 1

2

您可以做的是,您可以创建自己的自定义 SLOT ,而不是released()将按钮的信号直接连接到动画SLOT。start()然后将按钮连接到它,处理动作并调用动画。

首先阅读如何创建自定义 QWidget,而不是在main(). 简单的例子在这里

自定义小部件可能如下所示:

小部件.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

class QPushButton;
class QPropertyAnimation;

class MyWidget : public QWidget
{
    Q_OBJECT
public:
   MyWidget(QWidget *parent = 0);

private:
    QPushButton *button;
    QPropertyAnimation *animation;

public slots:
    void randomizeAnim();
};

#endif // WIDGET_H

小部件.cpp

#include "widget.h"
#include <QPushButton>
#include <QPropertyAnimation>
#include <ctime>

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent)
{
    button = new QPushButton("Push me!", this);
    animation = new QPropertyAnimation(button, "pos");
    animation->setDuration(0);

    QObject::connect(button, SIGNAL(released()), this, SLOT(randomizeAnim()));
}

void MyWidget::randomizeAnim()
{
    srand(time(0));
    int x = 1+(rand()%900);
    int y = 1+(rand()%400);

    animation->setEndValue(QPoint(x,y));
    animation->start();

}

现在您main.cpp可以简化为样板代码:

#include <QApplication>
#include "widget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QWidget *window = new MyWidget;
    window->resize(900,500);
    window->show();

    return a.exec();
}

每次单击时,您的自定义插槽都会处理动作并执行动画。

于 2012-08-27T20:46:09.393 回答