示例#1
0
void DiscountPage::setupItemAnimations()
{
    QState *smallState = new QState();
    QState *bigState = new QState();

    for (int i = 0; i < this->m_itemList.size(); i++) {
        smallState->assignProperty(this->m_itemList[i],"scale", 0);
        bigState->assignProperty(this->m_itemList[i],"scale",1);
    }

    QSequentialAnimationGroup *showItemGroup = new QSequentialAnimationGroup(this);
    for (int i = 0; i < this->m_itemList.size(); i++) {
        QPropertyAnimation *anim = new QPropertyAnimation(this->m_itemList[i], "scale", this);
        anim->setDuration(300);
        anim->setEasingCurve(QEasingCurve::OutBack);
        showItemGroup->addAnimation(anim);
    }

    QSignalTransition *trans = smallState->addTransition(this, SIGNAL(start()), bigState);
    trans->addAnimation(showItemGroup);
    connect(showItemGroup,SIGNAL(finished()),this,SLOT(startSelect()));

    trans = bigState->addTransition(this,SIGNAL(quitPage()),smallState);
    connect(smallState,SIGNAL(entered()),this,SLOT(closeSelect()));

    QStateMachine *states = new QStateMachine(this);
    states->addState(smallState);
    states->addState(bigState);
    states->setInitialState(smallState);

    states->start();
}
示例#2
0
void DockPanel::initShowHideAnimation()
{
    QStateMachine * machine = new QStateMachine(this);

    QState * showState = new QState(machine);
    showState->assignProperty(this,"y", 0);
    QState * hideState = new QState(machine);
    //y should change with DockMode changed
    connect(this, &DockPanel::startHide, [=]{
        hideState->assignProperty(this,"y", m_dockModeData->getDockHeight());
    });
    machine->setInitialState(showState);

    QPropertyAnimation *showAnimation = new QPropertyAnimation(this, "y");
    showAnimation->setDuration(SHOW_ANIMATION_DURATION);
    showAnimation->setEasingCurve(SHOW_EASINGCURVE);
    connect(showAnimation,&QPropertyAnimation::finished,this,&DockPanel::onShowPanelFinished);

    QPropertyAnimation *hideAnimation = new QPropertyAnimation(this, "y");
    hideAnimation->setDuration(HIDE_ANIMATION_DURATION);
    hideAnimation->setEasingCurve(HIDE_EASINGCURVE);
    connect(hideAnimation,&QPropertyAnimation::finished,this,&DockPanel::onHidePanelFinished);

    QSignalTransition *st = showState->addTransition(this,SIGNAL(startHide()), hideState);
    st->addAnimation(hideAnimation);
    QSignalTransition *ht = hideState->addTransition(this,SIGNAL(startShow()),showState);
    ht->addAnimation(showAnimation);

    machine->start();
}
示例#3
0
//! [3]
Q_DECL_EXPORT int main(int argc, char **argv)
{
    Application app(argc, argv);

    Factorial factorial;

    // Create the state machine
    QStateMachine machine;
//! [3]

//! [4]
    // Create the 'compute' state as child of the state machine
    QState *compute = new QState(&machine);

    // Initialize the 'fac', 'x' and 'xorig' properties of the Factorial object whenever the compute state is entered
    compute->assignProperty(&factorial, "fac", 1);
    compute->assignProperty(&factorial, "x", 6);
    compute->assignProperty(&factorial, "xorig", 6);

    /**
     * Add the custom transition to the compute state.
     * Note: This transition has the compute state as source and target state.
     */
    compute->addTransition(new FactorialLoopTransition(&factorial));
//! [4]

//! [5]
    // Create a final state
    QFinalState *done = new QFinalState(&machine);

    // Add a custom transition with the 'compute' state as source state and the 'done' state as target state
    FactorialDoneTransition *doneTransition = new FactorialDoneTransition(&factorial);
    doneTransition->setTargetState(done);
    compute->addTransition(doneTransition);
//! [5]

//! [6]
    // Set the 'compute' state as initial state of the state machine
    machine.setInitialState(compute);

    // Load the UI description from main.qml
    QmlDocument *qml = QmlDocument::create("asset:///main.qml");

    // Make the Factorial and StateMachine object available to the UI as context properties
    qml->setContextProperty("_factorial", &factorial);
    qml->setContextProperty("_machine", &machine);

    // Create the application scene
    AbstractPane *appPage = qml->createRootObject<AbstractPane>();
    Application::instance()->setScene(appPage);

    return Application::exec();
}
UIGraphicsZoomButton::UIGraphicsZoomButton(QIGraphicsWidget *pParent, const QIcon &icon, int iDirection)
    : UIGraphicsButton(pParent, icon)
    , m_iIndent(4)
    , m_iDirection(iDirection)
    , m_iAnimationDuration(200)
    , m_pStateMachine(0)
    , m_pForwardAnimation(0)
    , m_pBackwardAnimation(0)
    , m_fStateDefault(true)
{
    /* Setup: */
    setAcceptHoverEvents(true);

    /* Create state machine: */
    m_pStateMachine = new QStateMachine(this);

    /* Create 'default' state: */
    QState *pStateDefault = new QState(m_pStateMachine);
    pStateDefault->assignProperty(this, "stateDefault", true);

    /* Create 'zoomed' state: */
    QState *pStateZoomed = new QState(m_pStateMachine);
    pStateZoomed->assignProperty(this, "stateDefault", false);

    /* Initial state is 'default': */
    m_pStateMachine->setInitialState(pStateDefault);

    /* Zoom animation: */
    m_pForwardAnimation = new QPropertyAnimation(this, "geometry", this);
    m_pForwardAnimation->setDuration(m_iAnimationDuration);

    /* Unzoom animation: */
    m_pBackwardAnimation = new QPropertyAnimation(this, "geometry", this);
    m_pBackwardAnimation->setDuration(m_iAnimationDuration);

    /* Add state transitions: */
    QSignalTransition *pDefaultToZoomed = pStateDefault->addTransition(this, SIGNAL(sigHoverEnter()), pStateZoomed);
    pDefaultToZoomed->addAnimation(m_pForwardAnimation);

    QSignalTransition *pZoomedToDefault = pStateZoomed->addTransition(this, SIGNAL(sigHoverLeave()), pStateDefault);
    pZoomedToDefault->addAnimation(m_pBackwardAnimation);

    /* Start state-machine: */
    m_pStateMachine->start();
}
示例#5
0
//! [0]
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QPushButton button;
    QStateMachine machine;
//! [0]

//! [1]
    QState *off = new QState();
    off->assignProperty(&button, "text", "Off");
    off->setObjectName("off");

    QState *on = new QState();
    on->setObjectName("on");
    on->assignProperty(&button, "text", "On");
//! [1]

//! [2]
    off->addTransition(&button, SIGNAL(clicked()), on);
    on->addTransition(&button, SIGNAL(clicked()), off);
//! [2]

//! [3]
    machine.addState(off);
    machine.addState(on);
//! [3]

//! [4]
    machine.setInitialState(off);
    machine.start();
//! [4]

//! [5]
#if defined(Q_OS_SYMBIAN)
    button.showMaximized();
#elif defined(Q_WS_MAEMO_5) || defined(Q_WS_SIMULATOR)
    button.show();
#else
    button.resize(100, 50);
    button.show();
#endif
    return app.exec();
}
示例#6
0
文件: main.cpp 项目: elProxy/qtbase
//! [0]
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QPushButton button;
    QStateMachine machine;
//! [0]

//! [1]
    QState *off = new QState();
    off->assignProperty(&button, "text", "Off");
    off->setObjectName("off");

    QState *on = new QState();
    on->setObjectName("on");
    on->assignProperty(&button, "text", "On");
//! [1]

//! [2]
    off->addTransition(&button, SIGNAL(clicked()), on);
    on->addTransition(&button, SIGNAL(clicked()), off);
//! [2]

//! [3]
    machine.addState(off);
    machine.addState(on);
//! [3]

//! [4]
    machine.setInitialState(off);
    machine.start();
//! [4]

//! [5]
    button.resize(100, 50);
    button.show();
    return app.exec();
}
示例#7
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
// Загружаем интерфейс пользователя из формы и устанавливаем действия в меню
    ui->setupUi(this);
    connect(ui->action_start, SIGNAL(triggered()), ui->startButton, SLOT(click()));
    connect(ui->action_exit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->action_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(ui->action_help, SIGNAL(triggered()), this, SLOT(showHelp()));
    connect(ui->action_about, SIGNAL(triggered()), this, SLOT(showAbout()));
    connect(ui->action_tech, SIGNAL(triggered()), this, SLOT(showTz()));
// Заводим машину состояний
    QStateMachine *animation = new QStateMachine(this);
    QState *idle = new QState();
    QState *animating = new QState();
    animating->assignProperty(ui->startButton,"text", tr("&Стоп"));
    animating->assignProperty(ui->startButton,"icon", QIcon(":/icons/control-stop-square.png"));
    animating->assignProperty(ui->action_start,"text",tr("О&становить анимацию"));
    animating->assignProperty(ui->action_start,"icon", QIcon(":/icons/control-stop-square.png"));
    idle->assignProperty(ui->startButton,"text", tr("Пу&ск"));
    idle->assignProperty(ui->startButton,"icon", QIcon(":/icons/control.png"));
    idle->assignProperty(ui->action_start,"text",tr("Запу&стить анимацию"));
    idle->assignProperty(ui->action_start,"icon", QIcon(":/icons/control.png"));
    QSignalTransition *startTransition = new QSignalTransition(ui->startButton, SIGNAL(clicked()), idle);
    startTransition->setTargetState(animating);
    QSignalTransition *stopTransition = new QSignalTransition(ui->startButton, SIGNAL(clicked()), animating);
    stopTransition->setTargetState(idle);
    QSignalTransition *doneTransition = new QSignalTransition(ui->widget, SIGNAL(animationStopped()), animating);
    doneTransition->setTargetState(idle);
    connect(startTransition, SIGNAL(triggered()), ui->widget, SLOT(startAnimation()));
    connect(stopTransition, SIGNAL(triggered()), ui->widget, SLOT(stopAnimation()));
    idle->addTransition(startTransition);
    animating->addTransition(stopTransition);
    animating->addTransition(doneTransition);
    animation->addState(idle);
    animation->addState(animating);
    animation->setInitialState(idle);
    animation->start();
 // В Linux мячик иногда сразу не отображается...
    ui->widget->updateGL();
}
示例#8
0
void TMainWind::init()
{
	setCentralWidget(m_canvas = new TCanvas);

	QLabel* statusLabel = new QLabel;
	statusBar()->addPermanentWidget(statusLabel);

	QStateMachine* machine = new QStateMachine(this);
	QState* creation = new QState;
	QState* bending = new QState; // transformation
	QState* painting = new QState;
	QState* extrusion = new QState;

	creation->assignProperty(m_canvas, "mode", TCanvas::Creation);
	creation->assignProperty(statusLabel, "text", tr("Mode: Creation"));
	creation->addTransition(m_canvas, SIGNAL(creationFinished()), painting);
	
	bending->assignProperty(m_canvas, "mode", TCanvas::Bending);
	bending->assignProperty(statusLabel, "text", tr("Mode: Bending"));
	bending->addTransition(m_canvas, SIGNAL(bendingFinished()), painting);

	painting->assignProperty(m_canvas, "mode", TCanvas::Painting);
	painting->assignProperty(statusLabel, "text", tr("Mode: Painting"));
	painting->addTransition(m_canvas, SIGNAL(toEdit()), extrusion);

	extrusion->assignProperty(m_canvas, "mode", TCanvas::Extrusion);
	extrusion->assignProperty(statusLabel, "text", tr("Mode: Extrusion"));
	extrusion->addTransition(m_canvas, SIGNAL(extrusionFinished()), painting);

	bending->addTransition(m_canvas, SIGNAL(restart()), creation);
	painting->addTransition(m_canvas, SIGNAL(restart()), creation);
	extrusion->addTransition(m_canvas, SIGNAL(restart()), creation);
	

	machine->addState(creation);
	machine->addState(bending);
	machine->addState(painting);
	machine->addState(extrusion);
	machine->setInitialState(creation);
	machine->start();
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    stateMachine(new QStateMachine(this)),
    lastSelectDir(OP_DIR)
{
    ui->setupUi(this);
    ui->listWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
    //Setting states
    QState *runningState = new QState();
    QState *stopState = new QState();

    stopState->addTransition(this,SIGNAL(started()),runningState);
    runningState->addTransition(this,SIGNAL(finished()),stopState);

    runningState->assignProperty(ui->addButton,"enabled","false");
    runningState->assignProperty(ui->clearAllButton,"enabled","false");
    runningState->assignProperty(ui->removeButton,"enabled","false");


    stopState->assignProperty(ui->addButton,"enabled","true");
    stopState->assignProperty(ui->clearAllButton,"enabled","true");
    stopState->assignProperty(ui->removeButton,"enabled","true");

    connect(runningState,&QState::entered,[&]{
        qDebug()<<QTime::currentTime()<<"start convert";
    });
    connect(runningState,&QState::exited,[&]{
        qDebug()<<QTime::currentTime()<<"stop convert";
    });
    connect(runningState,&QState::exited,[&]{
        ui->progressBar->setValue(100);
        QMessageBox::information(
                    this,
                    tr("Nook HD+ Manga Converter"),
                    tr("All job completed!") );
    });

    stateMachine->addState(stopState);
    stateMachine->addState(runningState);
    stateMachine->setInitialState(stopState);

    connect(ui->convertButton,&QPushButton::clicked,this,&MainWindow::convert);
    connect(ui->addButton,&QPushButton::clicked,this,&MainWindow::addBook);
    connect(ui->clearAllButton,&QPushButton::clicked,ui->listWidget,&QListWidget::clear);
    connect(ui->removeButton,&QPushButton::clicked,[&]{qDeleteAll(ui->listWidget->selectedItems());});
    connect(this,&MainWindow::completed,ui->progressBar,&QProgressBar::setValue);
    stateMachine->start();
}
示例#10
0
ExampleView::ExampleView(QWidget* parent)
   : QFrame(parent)
      {
      _score = 0;
      setAcceptDrops(true);
      setFocusPolicy(Qt::StrongFocus);
      resetMatrix();
      _fgPixmap = nullptr;
      if (preferences.getBool(PREF_UI_CANVAS_FG_USECOLOR))
            _fgColor = preferences.getColor(PREF_UI_CANVAS_FG_COLOR);
      else {
            _fgPixmap = new QPixmap(preferences.getString(PREF_UI_CANVAS_FG_WALLPAPER));
            if (_fgPixmap == 0 || _fgPixmap->isNull())
                  qDebug("no valid pixmap %s", qPrintable(preferences.getString(PREF_UI_CANVAS_FG_WALLPAPER)));
            }
      // setup drag canvas state
      sm          = new QStateMachine(this);
      QState* stateActive = new QState;

      QState* s1 = new QState(stateActive);
      s1->setObjectName("example-normal");
      s1->assignProperty(this, "cursor", QCursor(Qt::ArrowCursor));

      QState* s = new QState(stateActive);
      s->setObjectName("example-drag");
      s->assignProperty(this, "cursor", QCursor(Qt::SizeAllCursor));
      QEventTransition* cl = new QEventTransition(this, QEvent::MouseButtonRelease);
      cl->setTargetState(s1);
      s->addTransition(cl);
      s1->addTransition(new DragTransitionExampleView(this));


      sm->addState(stateActive);
      stateActive->setInitialState(s1);
      sm->setInitialState(stateActive);

      sm->start();
      }
示例#11
0
//! [0]
PadNavigator::PadNavigator(const QSize &size, QWidget *parent)
    : QGraphicsView(parent)
{
//! [0]
//! [1]
    // Splash item
    SplashItem *splash = new SplashItem;
    splash->setZValue(1);
//! [1]

//! [2]
    // Pad item
    FlippablePad *pad = new FlippablePad(size);
    QGraphicsRotation *flipRotation = new QGraphicsRotation(pad);
    QGraphicsRotation *xRotation = new QGraphicsRotation(pad);
    QGraphicsRotation *yRotation = new QGraphicsRotation(pad);
    flipRotation->setAxis(Qt::YAxis);
    xRotation->setAxis(Qt::YAxis);
    yRotation->setAxis(Qt::XAxis);
    pad->setTransformations(QList<QGraphicsTransform *>()
                            << flipRotation
                            << xRotation << yRotation);
//! [2]

//! [3]
    // Back (proxy widget) item
    QGraphicsProxyWidget *backItem = new QGraphicsProxyWidget(pad);
    QWidget *widget = new QWidget;
    form.setupUi(widget);
    form.hostName->setFocus();
    backItem->setWidget(widget);
    backItem->setVisible(false);
    backItem->setFocus();
    backItem->setCacheMode(QGraphicsItem::ItemCoordinateCache);
    const QRectF r = backItem->rect();
    backItem->setTransform(QTransform()
                           .rotate(180, Qt::YAxis)
                           .translate(-r.width()/2, -r.height()/2));
//! [3]

//! [4]
    // Selection item
    RoundRectItem *selectionItem = new RoundRectItem(QRectF(-60, -60, 120, 120), Qt::gray, pad);
    selectionItem->setZValue(0.5);
//! [4]

//! [5]
    // Splash animations
    QPropertyAnimation *smoothSplashMove = new QPropertyAnimation(splash, "y");
    QPropertyAnimation *smoothSplashOpacity = new QPropertyAnimation(splash, "opacity");
    smoothSplashMove->setEasingCurve(QEasingCurve::InQuad);
    smoothSplashMove->setDuration(250);
    smoothSplashOpacity->setDuration(250);
//! [5]

//! [6]
    // Selection animation
    QPropertyAnimation *smoothXSelection = new QPropertyAnimation(selectionItem, "x");
    QPropertyAnimation *smoothYSelection = new QPropertyAnimation(selectionItem, "y");
    QPropertyAnimation *smoothXRotation = new QPropertyAnimation(xRotation, "angle");
    QPropertyAnimation *smoothYRotation = new QPropertyAnimation(yRotation, "angle");
    smoothXSelection->setDuration(125);
    smoothYSelection->setDuration(125);
    smoothXRotation->setDuration(125);
    smoothYRotation->setDuration(125);
    smoothXSelection->setEasingCurve(QEasingCurve::InOutQuad);
    smoothYSelection->setEasingCurve(QEasingCurve::InOutQuad);
    smoothXRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothYRotation->setEasingCurve(QEasingCurve::InOutQuad);
//! [6]

//! [7]
    // Flip animation setup
    QPropertyAnimation *smoothFlipRotation = new QPropertyAnimation(flipRotation, "angle");
    QPropertyAnimation *smoothFlipScale = new QPropertyAnimation(pad, "scale");
    QPropertyAnimation *smoothFlipXRotation = new QPropertyAnimation(xRotation, "angle");
    QPropertyAnimation *smoothFlipYRotation = new QPropertyAnimation(yRotation, "angle");
    QParallelAnimationGroup *flipAnimation = new QParallelAnimationGroup(this);
    smoothFlipScale->setDuration(500);
    smoothFlipRotation->setDuration(500);
    smoothFlipXRotation->setDuration(500);
    smoothFlipYRotation->setDuration(500);
    smoothFlipScale->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipXRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipYRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipScale->setKeyValueAt(0, qvariant_cast<qreal>(1.0));
    smoothFlipScale->setKeyValueAt(0.5, qvariant_cast<qreal>(0.7));
    smoothFlipScale->setKeyValueAt(1, qvariant_cast<qreal>(1.0));
    flipAnimation->addAnimation(smoothFlipRotation);
    flipAnimation->addAnimation(smoothFlipScale);
    flipAnimation->addAnimation(smoothFlipXRotation);
    flipAnimation->addAnimation(smoothFlipYRotation);
//! [7]

//! [8]
    // Flip animation delayed property assignment
    QSequentialAnimationGroup *setVariablesSequence = new QSequentialAnimationGroup;
    QPropertyAnimation *setFillAnimation = new QPropertyAnimation(pad, "fill");
    QPropertyAnimation *setBackItemVisibleAnimation = new QPropertyAnimation(backItem, "visible");
    QPropertyAnimation *setSelectionItemVisibleAnimation = new QPropertyAnimation(selectionItem, "visible");
    setFillAnimation->setDuration(0);
    setBackItemVisibleAnimation->setDuration(0);
    setSelectionItemVisibleAnimation->setDuration(0);
    setVariablesSequence->addPause(250);
    setVariablesSequence->addAnimation(setBackItemVisibleAnimation);
    setVariablesSequence->addAnimation(setSelectionItemVisibleAnimation);
    setVariablesSequence->addAnimation(setFillAnimation);
    flipAnimation->addAnimation(setVariablesSequence);
//! [8]

//! [9]
    // Build the state machine
    QStateMachine *stateMachine = new QStateMachine(this);
    QState *splashState = new QState(stateMachine);
    QState *frontState = new QState(stateMachine);
    QHistoryState *historyState = new QHistoryState(frontState);
    QState *backState = new QState(stateMachine);
//! [9]
//! [10]
    frontState->assignProperty(pad, "fill", false);
    frontState->assignProperty(splash, "opacity", 0.0);
    frontState->assignProperty(backItem, "visible", false);
    frontState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(0.0));
    frontState->assignProperty(selectionItem, "visible", true);
    backState->assignProperty(pad, "fill", true);
    backState->assignProperty(backItem, "visible", true);
    backState->assignProperty(xRotation, "angle", qvariant_cast<qreal>(0.0));
    backState->assignProperty(yRotation, "angle", qvariant_cast<qreal>(0.0));
    backState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(180.0));
    backState->assignProperty(selectionItem, "visible", false);
    stateMachine->addDefaultAnimation(smoothXRotation);
    stateMachine->addDefaultAnimation(smoothYRotation);
    stateMachine->addDefaultAnimation(smoothXSelection);
    stateMachine->addDefaultAnimation(smoothYSelection);
    stateMachine->setInitialState(splashState);
//! [10]

//! [11]
    // Transitions
    QEventTransition *anyKeyTransition = new QEventTransition(this, QEvent::KeyPress, splashState);
    anyKeyTransition->setTargetState(frontState);
    anyKeyTransition->addAnimation(smoothSplashMove);
    anyKeyTransition->addAnimation(smoothSplashOpacity);
//! [11]

//! [12]
    QKeyEventTransition *enterTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                   Qt::Key_Enter, backState);
    QKeyEventTransition *returnTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                    Qt::Key_Return, backState);
    QKeyEventTransition *backEnterTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                       Qt::Key_Enter, frontState);
    QKeyEventTransition *backReturnTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Return, frontState);
    enterTransition->setTargetState(historyState);
    returnTransition->setTargetState(historyState);
    backEnterTransition->setTargetState(backState);
    backReturnTransition->setTargetState(backState);
    enterTransition->addAnimation(flipAnimation);
    returnTransition->addAnimation(flipAnimation);
    backEnterTransition->addAnimation(flipAnimation);
    backReturnTransition->addAnimation(flipAnimation);
//! [12]

//! [13]
    // Create substates for each icon; store in temporary grid.
    int columns = size.width();
    int rows = size.height();
    QVector< QVector< QState * > > stateGrid;
    stateGrid.resize(rows);
    for (int y = 0; y < rows; ++y) {
        stateGrid[y].resize(columns);
        for (int x = 0; x < columns; ++x)
            stateGrid[y][x] = new QState(frontState);
    }
    frontState->setInitialState(stateGrid[0][0]);
    selectionItem->setPos(pad->iconAt(0, 0)->pos());
//! [13]

//! [14]
    // Enable key navigation using state transitions
    for (int y = 0; y < rows; ++y) {
        for (int x = 0; x < columns; ++x) {
            QState *state = stateGrid[y][x];
            QKeyEventTransition *rightTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                           Qt::Key_Right, state);
            QKeyEventTransition *leftTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Left, state);
            QKeyEventTransition *downTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Down, state);
            QKeyEventTransition *upTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Up, state);
            rightTransition->setTargetState(stateGrid[y][(x + 1) % columns]);
            leftTransition->setTargetState(stateGrid[y][((x - 1) + columns) % columns]);
            downTransition->setTargetState(stateGrid[(y + 1) % rows][x]);
            upTransition->setTargetState(stateGrid[((y - 1) + rows) % rows][x]);
//! [14]
//! [15]
            RoundRectItem *icon = pad->iconAt(x, y);
            state->assignProperty(xRotation, "angle", -icon->x() / 6.0);
            state->assignProperty(yRotation, "angle", icon->y() / 6.0);
            state->assignProperty(selectionItem, "x", icon->x());
            state->assignProperty(selectionItem, "y", icon->y());
            frontState->assignProperty(icon, "visible", true);
            backState->assignProperty(icon, "visible", false);

            QPropertyAnimation *setIconVisibleAnimation = new QPropertyAnimation(icon, "visible");
            setIconVisibleAnimation->setDuration(0);
            setVariablesSequence->addAnimation(setIconVisibleAnimation);
        }
    }
//! [15]

//! [16]
    // Scene
    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setBackgroundBrush(QPixmap(":/images/blue_angle_swirl.jpg"));
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    scene->addItem(pad);
    scene->setSceneRect(scene->itemsBoundingRect());
    setScene(scene);
//! [16]

//! [17]
    // Adjust splash item to scene contents
    const QRectF sbr = splash->boundingRect();
    splash->setPos(-sbr.width() / 2, scene->sceneRect().top() - 2);
    frontState->assignProperty(splash, "y", splash->y() - 100.0);
    scene->addItem(splash);
//! [17]

//! [18]
    // View
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setMinimumSize(50, 50);
    setViewportUpdateMode(FullViewportUpdate);
    setCacheMode(CacheBackground);
    setRenderHints(QPainter::Antialiasing
                   | QPainter::SmoothPixmapTransform
                   | QPainter::TextAntialiasing);
#ifndef QT_NO_OPENGL
    setViewport(new QOpenGLWidget);
#endif

    stateMachine->start();
//! [18]
}
示例#12
0
// NB: resizeEvent should just change the positions & sizes. However,
// moving the first to last state transitions every time an item is
// added is a pain. This means that setGeometry on this widget must
// only be called after all items have been added.
void CarouselGraphicsWidget::resizeEvent(QResizeEvent *event)
{
	QSize size = event->size();

	// TODO view changes size, should we really be changeing the scene size?
	scene()->setSceneRect(0, 0, size.width(), size.height());

	// Use icons with same aspect ratio as VGA.
	int tw = size.width();
	int th = size.height();
	if (tw > th*640/480) tw = th*640/480;
	if (th > tw*480/640) th = tw*480/640;

	int iw = tw / 2;
	int ih = th / 2;
	int isw = tw * 3 / 16;
	int ish = th * 3 / 16;
	int w = (size.width()  - iw/2 - isw/2) / 2;
	int h = (size.height() - ih/2 - ish/2) / 2;
	int cx = size.width()/2;
	int cy = (size.height() - ish)/2;

	int num_objects = icons.size();


	for (int i=0; i<num_objects; ++i) {
		float angle = 2.0*PI*i / num_objects;
		QRect r;

		// When the icon is at the bottom of the screen (i=0), make it larger.
		// Though it would look nicer if the size was based on the 'depth', this
		// would involve a lot of scaling and then likely hit performance.
		if (i == 0)
			r.setRect(-iw/2, -ih/2, iw, ih);
		else
			r.setRect(-isw/2, -ish/2, isw, ish);
		r.translate(cx, cy);
		r.translate(w*sin(angle), h*cos(angle));

		for (int j=0; j<num_objects; ++j) {
			QState *state = states.at((i+j) % num_objects);
			QObject *o = icons.at((num_objects-j) % num_objects);

			// Set the position & make only the item at the bottom
			// of the widget clickable
			state->assignProperty(o, "geometry", r);
			state->assignProperty(o, "enabled", i==0); 
			state->assignProperty(o, "focus", i==0); 
		}
	}

	if (states.size() > 1) {
		QSignalTransition *transition;
		QState *firstState = states.at(0);
		QState *lastState = states.at(states.size()-1);

		// Link to the next state - special case
		transition = lastState->addTransition(this, SIGNAL(m_next()), firstState);
		transition->addAnimation(animationGroup);

		// Link to the previous state - special case
		transition = firstState->addTransition(this, SIGNAL(m_back()), lastState);
		transition->addAnimation(animationGroup);

		machine->start();
	}
}
示例#13
0
PadNavigator::PadNavigator( QWidget *parent)
    : QGraphicsView(parent)
{
    QSize size(6,2);

    // Pad item
    this->pad = new FlippablePad(size);

    // Selection item
    RoundRectItem *selectionItem = new RoundRectItem(QRectF(-110, -110, 220, 220),
                                                     Qt::gray, pad);
    selectionItem->setZValue(0.5);

    // Selection animation
    QPropertyAnimation *smoothXSelection = new QPropertyAnimation(selectionItem, "x");
    QPropertyAnimation *smoothYSelection = new QPropertyAnimation(selectionItem, "y");
    smoothXSelection->setDuration(100);
    smoothYSelection->setDuration(100);
    smoothXSelection->setEasingCurve(QEasingCurve::InCurve);
    smoothYSelection->setEasingCurve(QEasingCurve::InCurve);

    // Build the state machine
    QStateMachine *stateMachine = new QStateMachine(this);

    QState *frontState = new QState(stateMachine);

    frontState->assignProperty(pad, "fill", false);

    frontState->assignProperty(selectionItem, "visible", true);

    stateMachine->addDefaultAnimation(smoothXSelection);
    stateMachine->addDefaultAnimation(smoothYSelection);
    stateMachine->setInitialState(frontState);

    // Create substates for each icon; store in temporary grid.
    int columns = size.width();
    int rows = size.height();
    QVector< QVector< QState * > > stateGrid;
    stateGrid.resize(rows);
    for (int y = 0; y < rows; ++y) {
        stateGrid[y].resize(columns);
        for (int x = 0; x < columns; ++x)
            stateGrid[y][x] = new QState(frontState);
    }
    frontState->setInitialState(stateGrid[0][0]);
    selectionItem->setPos(pad->iconAt(0, 0)->pos());

    // Enable key navigation using state transitions
    for (int y = 0; y < rows; ++y) {
        for (int x = 0; x < columns; ++x) {
            QState *state = stateGrid[y][x];
            QKeyEventTransition *rightTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                           Qt::Key_Right, state);
            QKeyEventTransition *leftTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Left, state);
            QKeyEventTransition *downTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Down, state);
            QKeyEventTransition *upTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Up, state);

            rightTransition->setTargetState(stateGrid[y][(x + 1) % columns]);
            leftTransition->setTargetState(stateGrid[y][((x - 1) + columns) % columns]);
            downTransition->setTargetState(stateGrid[(y + 1) % rows][x]);
            upTransition->setTargetState(stateGrid[((y - 1) + rows) % rows][x]);

            RoundRectItem *icon = pad->iconAt(x, y);

            state->assignProperty(selectionItem, "x", icon->x());
            state->assignProperty(selectionItem, "y", icon->y());

        }
    }
    // Scene
    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    scene->addItem(pad);
    scene->setSceneRect(scene->itemsBoundingRect());
    setScene(scene);

    // View
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setMinimumSize(50, 50);
    setCacheMode(CacheBackground);
    setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);

    stateMachine->start();

}
示例#14
0
UIGraphicsRotatorButton::UIGraphicsRotatorButton(QIGraphicsWidget *pParent,
                                                 const QString &strPropertyName,
                                                 bool fToggled,
                                                 bool fReflected /* = false */,
                                                 int iAnimationDuration /* = 300 */)
    : UIGraphicsButton(pParent, UIIconPool::iconSet(":/expanding_collapsing_16px.png"))
    , m_fReflected(fReflected)
    , m_state(fToggled ? UIGraphicsRotatorButtonState_Rotated : UIGraphicsRotatorButtonState_Default)
    , m_pAnimationMachine(0)
    , m_iAnimationDuration(iAnimationDuration)
    , m_pForwardButtonAnimation(0)
    , m_pBackwardButtonAnimation(0)
    , m_pForwardSubordinateAnimation(0)
    , m_pBackwardSubordinateAnimation(0)
{
    /* Configure: */
    setAutoHandleButtonClick(true);

    /* Create state machine: */
    m_pAnimationMachine = new QStateMachine(this);
    /* Create 'default' state: */
    QState *pStateDefault = new QState(m_pAnimationMachine);
    pStateDefault->assignProperty(this, "state", QVariant::fromValue(UIGraphicsRotatorButtonState_Default));
    pStateDefault->assignProperty(this, "rotation", m_fReflected ? 180 : 0);
    /* Create 'animating' state: */
    QState *pStateAnimating = new QState(m_pAnimationMachine);
    pStateAnimating->assignProperty(this, "state", QVariant::fromValue(UIGraphicsRotatorButtonState_Animating));
    /* Create 'rotated' state: */
    QState *pStateRotated = new QState(m_pAnimationMachine);
    pStateRotated->assignProperty(this, "state", QVariant::fromValue(UIGraphicsRotatorButtonState_Rotated));
    pStateRotated->assignProperty(this, "rotation", 90);

    /* Forward button animation: */
    m_pForwardButtonAnimation = new QPropertyAnimation(this, "rotation", this);
    m_pForwardButtonAnimation->setDuration(m_iAnimationDuration);
    m_pForwardButtonAnimation->setStartValue(m_fReflected ? 180 : 0);
    m_pForwardButtonAnimation->setEndValue(90);
    /* Backward button animation: */
    m_pBackwardButtonAnimation = new QPropertyAnimation(this, "rotation", this);
    m_pBackwardButtonAnimation->setDuration(m_iAnimationDuration);
    m_pBackwardButtonAnimation->setStartValue(90);
    m_pBackwardButtonAnimation->setEndValue(m_fReflected ? 180 : 0);

    /* Forward subordinate animation: */
    m_pForwardSubordinateAnimation = new QPropertyAnimation(pParent, strPropertyName.toLatin1(), this);
    m_pForwardSubordinateAnimation->setDuration(m_iAnimationDuration);
    m_pForwardSubordinateAnimation->setEasingCurve(QEasingCurve::InCubic);
    /* Backward subordinate animation: */
    m_pBackwardSubordinateAnimation = new QPropertyAnimation(pParent, strPropertyName.toLatin1(), this);
    m_pBackwardSubordinateAnimation->setDuration(m_iAnimationDuration);
    m_pBackwardSubordinateAnimation->setEasingCurve(QEasingCurve::InCubic);

    /* Default => Animating: */
    QSignalTransition *pDefaultToAnimating = pStateDefault->addTransition(this, SIGNAL(sigToAnimating()), pStateAnimating);
    pDefaultToAnimating->addAnimation(m_pForwardButtonAnimation);
    pDefaultToAnimating->addAnimation(m_pForwardSubordinateAnimation);
    /* Animating => Rotated: */
    connect(m_pForwardButtonAnimation, SIGNAL(finished()), this, SIGNAL(sigToRotated()), Qt::QueuedConnection);
    pStateAnimating->addTransition(this, SIGNAL(sigToRotated()), pStateRotated);

    /* Rotated => Animating: */
    QSignalTransition *pRotatedToAnimating = pStateRotated->addTransition(this, SIGNAL(sigToAnimating()), pStateAnimating);
    pRotatedToAnimating->addAnimation(m_pBackwardButtonAnimation);
    pRotatedToAnimating->addAnimation(m_pBackwardSubordinateAnimation);
    /* Animating => Default: */
    connect(m_pBackwardButtonAnimation, SIGNAL(finished()), this, SIGNAL(sigToDefault()), Qt::QueuedConnection);
    pStateAnimating->addTransition(this, SIGNAL(sigToDefault()), pStateDefault);

    /* Default => Rotated: */
    pStateDefault->addTransition(this, SIGNAL(sigToRotated()), pStateRotated);

    /* Rotated => Default: */
    pStateRotated->addTransition(this, SIGNAL(sigToDefault()), pStateDefault);

    /* Initial state is 'default': */
    m_pAnimationMachine->setInitialState(!fToggled ? pStateDefault : pStateRotated);
    /* Start state-machine: */
    m_pAnimationMachine->start();

    /* Refresh: */
    refresh();
}
示例#15
0
void StateMachineMgr::buildStateMachine(QLayout* layout,bool bIsEntryLane)
{
    if(bIsEntryLane)
    {
        buildEntryWindows(layout);
    }
    else
    {
        buildExitWindows(layout);
    }
    //设备查看状态
    QState * devShowState = new MtcLaneState(&m_machine, m_devTable);
    //初始化状态
    QState * initState = new MtcLaneState(&m_machine, m_pFormLoadParam);
    //参数加载成功状态
    QState * loadSuccess = new MtcLaneState(&m_machine,m_pFormMsg);
    //加载参数成功时页面显示设置
    loadSuccess->assignProperty(m_pFormMsg, "message", tr("请放置身份卡\n按『上/下班』键登录"));
    loadSuccess->assignProperty(m_pFormMsg, "title", tr(""));
    //选择程序操作:退出程序、重启程序、关闭计算机、重启计算机
    QState *exitState = new MtcLaneState(&m_machine,m_pTableWidget);
    //工班选择状态
    QState * shiftState = new MtcLaneState(&m_machine, m_pTableWidget);
    //选择票号修改状态
    QState *IdTKstate=new MtcLaneState(&m_machine,m_pTableWidget);
    //修改票号页面状态
    QState *IdInform=new MtcLaneState(&m_machine,getInformWidget());
    //确认票号状态
    QState *confirmInvState = new MtcLaneState(&m_machine, m_pFormMsg);
    //正常上班状态
    QState* ordState = new MtcLaneState(&m_machine, m_pOrdWidget);
    //提示切换雨棚灯状态
    QState * turnOnLightState = new MtcLaneState(&m_machine, m_pFormMsg);

    turnOnLightState->assignProperty(m_pFormMsg, "message", tr("请按【雨棚开关】键\n将雨棚灯切换至绿灯"));
    //设备状态确认->初始化状态
    devShowState->addTransition(new TranConfirmDev(initState));
    //初始化状态->参数加载成功状态
    LoadParamTransition *tLoadParam = new LoadParamTransition(initState,SIGNAL(entered()));
    tLoadParam->setTargetState(loadSuccess);
    initState->addTransition(tLoadParam);
    //加载成功状态->选择程序退出状态
    TranExitApp *exitTrans = new TranExitApp(exitState);
    loadSuccess->addTransition(exitTrans);
    //加载成功状态->闯关tran->加载成功状态
    addRushTranLogOut(loadSuccess);
    //选择程序退出状态->执行退出操作
    TranSelectExitApp *exitAppTrans = new TranSelectExitApp(loadSuccess);
    exitState->addTransition(exitAppTrans);
    //退出程序操作,返回初始化界面
    TranQuitSelect *quitselTrans = new TranQuitSelect(loadSuccess);
    exitState->addTransition(quitselTrans);
    //选择工班时出现闯关
    addRushTranLogOut(shiftState);


    //上班后出现闯关
    QHistoryState* rushState = new QHistoryState(ordState);
    TranRushLogin* tranLogin = new TranRushLogin(getDeviceFactory()->getIOBoard(), SIGNAL(InputChanged(quint32,quint8)));
    tranLogin->setTargetState(rushState);
    ordState->addTransition(tranLogin);
    //上班后收费员按F12键,切换菜单
    QHistoryState* showLogState = new QHistoryState(ordState);
    TranChangeVpr* tranVpr = new TranChangeVpr(showLogState);
    ordState->addTransition(tranVpr);

    //建立上班后子状态机
    m_pOrdWidget->initStateMachine(ordState, loadSuccess);
    //加载参数成功->用户验证身份
    TranShift *tShowPassword = new TranShift(shiftState);
    loadSuccess->addTransition(tShowPassword);

    //打开雨棚灯状态闯关
    addRushTranLogOut(turnOnLightState);
    //打开雨棚灯状态->正常上班状态
    TranTurnOnCanLight* tOrd = new TranTurnOnCanLight(ordState);
    turnOnLightState->addTransition(tOrd);

    //确认卡盒卡ID操作,模拟实现
    TranCardBox *tGotoLight = new TranCardBox(turnOnLightState);

    //入口没有票号处理
    if(getLaneInfo()->isEntryLane())
    {
        shiftState->addTransition(new TranEntryConfirmShift(turnOnLightState));
    }
    else
    {
        //下班时票号操作
        QState *logOutIdState=new MtcLaneState(&m_machine,m_pTableWidget);
        QState *logOutInform=new MtcLaneState(&m_machine,getInformWidget());
        loadSuccess->addTransition(new TranShowInvoiceMenu(logOutIdState));
        logOutIdState->addTransition(new TranModifyInvoice(logOutInform));
        logOutIdState->addTransition(new TranChangeUpInvoice(logOutInform));
        logOutInform->addTransition(new TranFinInvoice(loadSuccess));
        logOutIdState->addTransition(new TranRtInvConfirm(loadSuccess));
        logOutInform->addTransition(new TranRtInvConfirm(loadSuccess));

        //确认班次,用户从班次中选择一个班次上班,班次记录到LaneInfo
        TranConfirmShift *tConfirm = new TranConfirmShift(confirmInvState);
        shiftState->addTransition(tConfirm);
        //修改票号时出现闯关
        addRushTranLogOut(IdTKstate);
        //修改票号时出现闯关
        addRushTranLogOut(IdInform);
        //确认票号状态闯关
        addRushTranLogOut(confirmInvState);
        //选择票号处理菜单,包括票据换上、修改票号
        TranShowInvoiceMenu * tMessIDTick = new TranShowInvoiceMenu(IdTKstate);
        confirmInvState->addTransition(tMessIDTick);
        //显示插入票号页面
        TranChangeUpInvoice *tInsertTK=new TranChangeUpInvoice(IdInform);//跳转到票号输入页面
        IdTKstate->addTransition(tInsertTK);
        //显示修改票号页面
        TranModifyInvoice *tInformTK=new TranModifyInvoice(IdInform);
        IdTKstate->addTransition(tInformTK);
        //完成票号操作,跳转票号确认状态
        TranFinInvoice *tShowInform=new TranFinInvoice(confirmInvState); //从页面输入和修改跳转到票号页面
        IdInform->addTransition(tShowInform);
        //输入修改票号跳转
        TranRtInvConfirm *treturntable=new TranRtInvConfirm(confirmInvState);
        IdInform->addTransition(treturntable);
        IdTKstate->addTransition(new TranRtInvConfirm(confirmInvState));
        //显示确认卡盒卡界面
        confirmInvState->addTransition(tGotoLight);
    }
    //返回等待上班状态
    shiftState->addTransition(new SpecialKeySignalTransition(loadSuccess, KeyEsc, KC_Func));
    confirmInvState->addTransition(new SpecialKeySignalTransition(loadSuccess, KeyEsc, KC_Func));
    //跳转到功能页面
    m_machine.setInitialState(devShowState);
    m_machine.start();
    //上班前功能界面
    loadSuccess->addTransition(new TranLogOutFunc(loadSuccess));
    QTimer::singleShot(1000, this, SLOT(beginInitState()));
}
示例#16
0
UIGChooserItem::UIGChooserItem(UIGChooserItem *pParent, bool fTemporary)
    : m_fRoot(!pParent)
    , m_fTemporary(fTemporary)
    , m_pParent(pParent)
    , m_iPreviousMinimumWidthHint(0)
    , m_iPreviousMinimumHeightHint(0)
    , m_dragTokenPlace(DragToken_Off)
    , m_fHovered(false)
    , m_pHighlightMachine(0)
    , m_pForwardAnimation(0)
    , m_pBackwardAnimation(0)
    , m_iAnimationDuration(400)
    , m_iDefaultDarkness(100)
    , m_iHighlightDarkness(90)
    , m_iAnimationDarkness(m_iDefaultDarkness)
    , m_iDragTokenDarkness(110)
{
    /* Install Chooser-view item accessibility interface factory: */
    QAccessible::installFactory(UIAccessibilityInterfaceForUIGChooserItem::pFactory);

    /* Basic item setup: */
    setOwnedByLayout(false);
    setAcceptDrops(true);
    setFocusPolicy(Qt::NoFocus);
    setFlag(QGraphicsItem::ItemIsSelectable, false);
    setAcceptHoverEvents(!isRoot());

    /* Non-root item? */
    if (!isRoot())
    {
        /* Create state machine: */
        m_pHighlightMachine = new QStateMachine(this);
        /* Create 'default' state: */
        QState *pStateDefault = new QState(m_pHighlightMachine);
        pStateDefault->assignProperty(this, "animationDarkness", m_iDefaultDarkness);
        /* Create 'highlighted' state: */
        QState *pStateHighlighted = new QState(m_pHighlightMachine);
        pStateHighlighted->assignProperty(this, "animationDarkness", m_iHighlightDarkness);

        /* Forward animation: */
        m_pForwardAnimation = new QPropertyAnimation(this, "animationDarkness", this);
        m_pForwardAnimation->setDuration(m_iAnimationDuration);
        m_pForwardAnimation->setStartValue(m_iDefaultDarkness);
        m_pForwardAnimation->setEndValue(m_iHighlightDarkness);

        /* Backward animation: */
        m_pBackwardAnimation = new QPropertyAnimation(this, "animationDarkness", this);
        m_pBackwardAnimation->setDuration(m_iAnimationDuration);
        m_pBackwardAnimation->setStartValue(m_iHighlightDarkness);
        m_pBackwardAnimation->setEndValue(m_iDefaultDarkness);

        /* Add state transitions: */
        QSignalTransition *pDefaultToHighlighted = pStateDefault->addTransition(this, SIGNAL(sigHoverEnter()), pStateHighlighted);
        pDefaultToHighlighted->addAnimation(m_pForwardAnimation);
        QSignalTransition *pHighlightedToDefault = pStateHighlighted->addTransition(this, SIGNAL(sigHoverLeave()), pStateDefault);
        pHighlightedToDefault->addAnimation(m_pBackwardAnimation);

        /* Initial state is 'default': */
        m_pHighlightMachine->setInitialState(pStateDefault);
        /* Start state-machine: */
        m_pHighlightMachine->start();
    }
}
SmoozikSimplestClientWindow::SmoozikSimplestClientWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SmoozikSimplestClientWindow)
{
    ui->setupUi(this);

    // Initialize SmoozikManager
    smoozikManager = new SmoozikManager(APIKEY, SECRET, SmoozikManager::XML, false, this);
    smoozikPlaylist = new SmoozikPlaylist;
    connect(smoozikManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(processNetworkReply(QNetworkReply*)));

    // Initialize music directory
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    _dirName = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
#else
    _dirName = QStandardPaths::writableLocation(QStandardPaths::MusicLocation);
#endif

    // Initialize playlist filler
    ui->setupUi(this);
    smoozikPlaylistFillerThread = new QThread();
    smoozikPlaylistFiller = new SmoozikPlaylistFiller(smoozikPlaylist);
    smoozikPlaylistFiller->moveToThread(smoozikPlaylistFillerThread);
    connect(smoozikPlaylistFiller, SIGNAL(trackFound(QString,QString,QString,QString,uint)), this, SLOT(addTrackToPlaylist(QString,QString,QString,QString,uint)));
    connect(smoozikPlaylistFiller, SIGNAL(tracksRetrieved()), this, SIGNAL(tracksRetrieved()));
    connect(smoozikPlaylistFiller, SIGNAL(noTrackRetrieved()), this, SLOT(noTrackRetrievedMessage()));
    connect(smoozikPlaylistFiller, SIGNAL(maxPlaylistSizeReached()), this, SLOT(maxPlaylistSizeReachedMessage()));
    connect(smoozikPlaylistFillerThread, SIGNAL(started()), smoozikPlaylistFiller, SLOT(fillPlaylist()));
    connect(smoozikPlaylistFiller, SIGNAL(finished()), smoozikPlaylistFillerThread, SLOT(quit()), Qt::DirectConnection);

    // Initialize player
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    player = new Phonon::MediaObject(this);
    Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
    Phonon::createPath(player, audioOutput);
    connect(player, SIGNAL(currentSourceChanged(Phonon::MediaSource)), this, SLOT(updateTrackLabels()));
    connect(player, SIGNAL(stateChanged(Phonon::State,Phonon::State)), this, SLOT(playerStateChanged()));
#else
    player = new QMediaPlayer(this);
    player->setPlaylist(new QMediaPlaylist(player));
    player->playlist()->setPlaybackMode(QMediaPlaylist::Sequential);
    connect(player, SIGNAL(currentMediaChanged(QMediaContent)), this, SLOT(updateTrackLabels()));
    connect(player, SIGNAL(stateChanged(QMediaPlayer::State)), this, SLOT(playerStateChanged()));
#endif
    connect(ui->playButton, SIGNAL(clicked()), player, SLOT(play()));
    connect(ui->pauseButton, SIGNAL(clicked()), player, SLOT(pause()));
    connect(this, SIGNAL(currentTrackSet()), this, SLOT(updateTrackLabels()));
    connect(this, SIGNAL(nextTrackSet()), this, SLOT(updateTrackLabels()));

    // Initialize main state machine which controls what is displayed
    QStateMachine *mainStateMachine = new QStateMachine(this);
    QState *mainState = new QState(mainStateMachine);
    QState *loginState = new QState(mainState);
    QState *startPartyState = new QState(mainState);
    QState *connectedState = new QState(mainState);
    QState *retrieveTracksState = new QState(connectedState);
    QState *sendPlaylistState = new QState(connectedState);
    QState *getTopTracksState = new QState(connectedState);
    QState *partyState = new QState(connectedState);
    QState *waitingState = new QState(partyState);
    QState *sendCurrentTrackState = new QState(partyState);
    QState *sendNextTrackState = new QState(partyState);

    QStateMachine *playerStateMachine = new QStateMachine(this);
    QState *playerState = new QState(playerStateMachine);
    QState *playingState = new QState(playerState);
    QState *pausedState = new QState(playerState);

    // Define state initial states and transitions
    mainStateMachine->setInitialState(mainState);
    mainState->setInitialState(loginState);
    connectedState->setInitialState(retrieveTracksState);
    partyState->setInitialState(waitingState);
    playerStateMachine->setInitialState(playerState);
    playerState->setInitialState(pausedState);

    mainState->addTransition(this, SIGNAL(disconnected()), loginState);
    loginState->addTransition(this, SIGNAL(loggedIn()), startPartyState);
    startPartyState->addTransition(this, SIGNAL(partyStarted()), connectedState);
    connectedState->addTransition(ui->changePlaylistButton, SIGNAL(clicked()), retrieveTracksState);
    retrieveTracksState->addTransition(this, SIGNAL(tracksRetrieved()), sendPlaylistState);
    sendPlaylistState->addTransition(this, SIGNAL(playlistSent()), getTopTracksState);
    getTopTracksState->addTransition(this, SIGNAL(currentTrackSet()), sendCurrentTrackState);
    sendCurrentTrackState->addTransition(this, SIGNAL(currentTrackSent()), getTopTracksState);
    getTopTracksState->addTransition(this, SIGNAL(nextTrackSet()), sendNextTrackState);
    sendNextTrackState->addTransition(this, SIGNAL(nextTrackSent()), waitingState);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    waitingState->addTransition(player, SIGNAL(currentSourceChanged(Phonon::MediaSource)), sendCurrentTrackState);
#else
    waitingState->addTransition(player, SIGNAL(currentMediaChanged(QMediaContent)), sendCurrentTrackState);
#endif

    playerState->addTransition(this, SIGNAL(playing()), playingState);
    playerState->addTransition(this, SIGNAL(paused()), pausedState);

    // Define state properties
    loginState->assignProperty(this, "state", Login);
    loginState->assignProperty(ui->stackedWidget, "currentIndex", ui->stackedWidget->indexOf(ui->loginPage));
    loginState->assignProperty(ui->loginButton, "enabled", true);
    loginState->assignProperty(ui->disconnectButton, "visible", false);
    loginState->assignProperty(ui->changePlaylistButton, "visible", false);
    loginState->assignProperty(ui->usernameLineEdit, "enabled", true);
    loginState->assignProperty(ui->passwordLineEdit, "enabled", true);
    loginState->assignProperty(ui->loginStateLabel, "text", QString());

    startPartyState->assignProperty(this, "state", StartParty);
    startPartyState->assignProperty(ui->loginStateLabel, "text", tr("Starting party..."));
    startPartyState->assignProperty(ui->disconnectButton, "visible", false);
    startPartyState->assignProperty(ui->changePlaylistButton, "visible", false);

    connectedState->assignProperty(ui->disconnectButton, "visible", true);

    retrieveTracksState->assignProperty(ui->stackedWidget, "currentIndex", ui->stackedWidget->indexOf(ui->loadingPage));
    retrieveTracksState->assignProperty(ui->loginStateLabel, "text", tr("Connected"));
    retrieveTracksState->assignProperty(ui->loadingLabel, "text", tr("Retrieving tracks..."));
    retrieveTracksState->assignProperty(ui->changePlaylistButton, "visible", false);

    sendPlaylistState->assignProperty(this, "state", SendPlaylist);
    sendPlaylistState->assignProperty(ui->loadingLabel, "text", tr("Sending playlist..."));
    sendPlaylistState->assignProperty(ui->changePlaylistButton, "visible", true);

    getTopTracksState->assignProperty(this, "state", GetTopTracks);
    getTopTracksState->assignProperty(ui->loadingLabel, "text", tr("Get top tracks..."));
    getTopTracksState->assignProperty(ui->nextButton, "enabled", false);
    getTopTracksState->assignProperty(ui->changePlaylistButton, "visible", true);

    partyState->assignProperty(ui->stackedWidget, "currentIndex", ui->stackedWidget->indexOf(ui->playerPage));
    partyState->assignProperty(ui->changePlaylistButton, "visible", true);

    sendCurrentTrackState->assignProperty(this, "state", SendCurrentTrack);
    sendCurrentTrackState->assignProperty(ui->nextButton, "enabled", false);

    sendNextTrackState->assignProperty(this, "state", SendNextTrack);
    sendNextTrackState->assignProperty(ui->nextButton, "enabled", false);

    waitingState->assignProperty(ui->nextButton, "enabled", true);

    playingState->assignProperty(ui->playButton, "visible", false);
    playingState->assignProperty(ui->pauseButton, "visible", true);

    pausedState->assignProperty(ui->playButton, "visible", true);
    pausedState->assignProperty(ui->pauseButton, "visible", false);

    // Connect states and actions
    connect(startPartyState, SIGNAL(entered()), this, SLOT(startParty()));
    connect(retrieveTracksState, SIGNAL(entered()), this, SLOT(retrieveTracksDialog()));
    connect(sendPlaylistState, SIGNAL(entered()), this, SLOT(sendPlaylist()));
    connect(getTopTracksState, SIGNAL(entered()), this, SLOT(getTopTracks()));
    connect(sendCurrentTrackState, SIGNAL(entered()), this, SLOT(sendCurrentTrack()));
    connect(sendNextTrackState, SIGNAL(entered()), this, SLOT(sendNextTrack()));

    // Connect gui and actions
    connect(ui->usernameLineEdit, SIGNAL(returnPressed()), this, SLOT(submitLogin()));
    connect(ui->passwordLineEdit, SIGNAL(returnPressed()), this, SLOT(submitLogin()));
    connect(ui->loginButton, SIGNAL(clicked()), this, SLOT(submitLogin()));
    connect(ui->nextButton, SIGNAL(clicked()), this, SLOT(nextTrack()));
    connect(ui->disconnectButton, SIGNAL(clicked()), this, SLOT(disconnect()));

    // Start state machine
    mainStateMachine->start();
    playerStateMachine->start();
}