在Qt Gui中如何使每个点击随机出现一个按钮

时间:2012-08-27 20:17:32

标签: c++ qt

好吧有没有办法让这个程序在每次点击按钮时随机改变变量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();
}  

1 个答案:

答案 0 :(得分:2)

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

首先阅读如何创建自定义QWidget,而不是在main()中创建顶级对象。 Simple example here

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

<强> widget.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

<强> widget.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();
}

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