confirmpopup.cpp 1.89 KB
#include "confirmpopup.h"
#include "ui_confirmpopup.h"

#include <QKeyEvent>

#include "soundplayer.h"

ConfirmPopup::ConfirmPopup(QWidget *parent, QString text) :
    QWidget(parent),
    ui(new Ui::ConfirmPopup)
{
    ui->setupUi(this);
    ui->text->setText(text);

    foreach (QPushButton *button, findChildren<QPushButton *>())
        connect(button, &QPushButton::pressed, SoundPlayer::playClick);

    setFocus();
}

ConfirmPopup::~ConfirmPopup()
{
    delete ui;
}

void ConfirmPopup::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case 0x01000030:    // Turn left
        onEncoderLeft();
        break;
    case 0x01000031:    // Push
        pushed = focusWidget();
        break;
    case 0x01000032:    // Turn right
        onEncoderRight();
        break;
    }
}

void ConfirmPopup::keyReleaseEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case 0x01000030:    // Turn left
        onEncoderLeft();
        break;
    case 0x01000031:    // Push
        if (focusWidget() == pushed)
            onEncoderClicked(pushed);

        pushed = NULL;
        break;
    case 0x01000032:    // Turn right
        onEncoderRight();
        break;
    }
}

void ConfirmPopup::on_okButton_clicked()
{
    deleteLater();
    emit accepted();
}

void ConfirmPopup::on_cancelButton_clicked()
{
    deleteLater();
    emit rejected();
}

void ConfirmPopup::onEncoderLeft()
{
    QWidget *focused = focusWidget();
    if (focused == this || focused == ui->okButton)
        ui->cancelButton->setFocus();
    else
        focusPreviousChild();
}

void ConfirmPopup::onEncoderRight()
{
    QWidget *focused = focusWidget();
    if (focused == this || focused == ui->cancelButton)
        ui->okButton->setFocus();
    else
        focusNextChild();
}

void ConfirmPopup::onEncoderClicked(QWidget *clicked)
{
    QPushButton *b = qobject_cast<QPushButton *>(clicked);
    if (b)
        b->click();
}