Qt / C ++ обнаруживает QPushButton при воспроизведении звука - PullRequest
1 голос
/ 15 марта 2020

Я хотел бы воспроизвести звук в моем приложении, когда один из моих QPushButton наведен курсором мыши.

Я начинаю изучать C ++, и я пытался написать это:

onhover .h

#ifndef ONHOVER_H
#define ONHOVER_H

#include <QDebug>
#include <QApplication>
#include <QWidget>
#include <QPushButton>

class onhover : public QPushButton
{
    Q_OBJECT

    public:
    onhover() {
        setMouseTracking(true);
        setMinimumSize(100, 100);
    }

    public: Q_SIGNALS:
    void hovered();

    protected:
    virtual void enterEvent( QEvent* e );

};

#endif // ONHOVER_H

mainwindow. cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"


#include <QDesktopServices>
#include <QProcess>
#include <qurl.h>
#include <QMessageBox>
#include <QSettings>
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <QByteRef>
#include <QMetaType>
#include <QByteArray>
#include <QFile>
#include <QtMultimedia/QSound>
#include <QObject>
#include <QMouseEvent>
#include <QEvent>
#include <QtMultimedia/QMediaPlayer>
#include <QFileInfo>
#include "onhover.h"
#include <QWidget>

using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

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

bool is_readable( const std::string & file )
{
    std::ifstream fichier( file.c_str() );
    return (bool) fichier != 0;
}

void onhover::enterEvent( QEvent* e )
{
    Q_EMIT hovered();

    // don't forget to forward the event
    QWidget::enterEvent( e );
}


void MainWindow::on_ConfigORCA_clicked()
{
    QMediaPlayer *player = new QMediaPlayer;
    player->setMedia(QUrl::fromLocalFile(QFileInfo("Sound/7-AccesHandicap.ogg.wav").absoluteFilePath()));
    player->setVolume(50);
    player->play();
    QProcess *myProcess1 = new QProcess(this);
    myProcess1->startDetached("kcmshell5 kcmaccess");
}

void MainWindow::on_Discord_clicked()
{
    QMediaPlayer *player = new QMediaPlayer;
    player->setMedia(QUrl::fromLocalFile(QFileInfo("Sound/10-DiscordLink.ogg.wav").absoluteFilePath()));
    player->setVolume(50);
    player->play();
    QDesktopServices::openUrl(QUrl("https://discord.gg/zG7g8cU", QUrl::TolerantMode));
}

void MainWindow::on_NoComprendo_clicked()
{
    using std::cout;
    if ( is_readable( "/usr/bin/nocomprendo" ) )
    {
        QProcess *myProcess3 = new QProcess(this);
        myProcess3->startDetached("/usr/bin/nocomprendo");
    }
    else
    {
        /* Le fichier n'existe pas */
        QMessageBox::warning(this, "NoComprendo Non Installé", "Veuillez suivre les instructions d'installation sur la page web qui va s'ouvrir");
        QDesktopServices::openUrl(QUrl("https://github.com/handyopensource/dvkbuntu-script-tts", QUrl::TolerantMode));
    }
}

void MainWindow::on_OuvrirNavigateur_clicked()
{
    QDesktopServices::openUrl(QUrl("file:///home/Accueil_local/index.html", QUrl::TolerantMode));
}

void MainWindow::on_OuvrirKmag_clicked()
{
    QProcess *myProcess3 = new QProcess(this);
    myProcess3->startDetached("/usr/bin/kmag");
}

void MainWindow::on_OuvrirSiteWeb_clicked()
{
    QDesktopServices::openUrl(QUrl("https://www.dvkbuntu.org", QUrl::TolerantMode));
}

void MainWindow::on_Contacts_clicked()
{
    QDesktopServices::openUrl(QUrl("mailto:handyopensourcedvkbuntu@gmail.com?subject=DVKBuntu&body=Bonjour \n \n \nCordialement\nPrénom Nom"));
}

void MainWindow::on_ScaleFactor_valueChanged(int value)
{
    float fvalue = value;
    scale=fvalue/10;

    ostringstream newscale;
    newscale<<scale;

    QString newnewscale = QString::fromStdString(newscale.str());

    QProcess::startDetached("/opt/dvkbuntu-menu-acceuil/ScaleFactor.sh", QStringList {newnewscale});
}

void MainWindow::on_ScaleFactor_sliderReleased()
{
    //QByteArray arrayScale(reinterpret_cast<const char*>(&scale),sizeof(scale));
    //qputenv("QT_SCALE_FACTOR",arrayScale);
    QMessageBox messageBox;
    QString textScale;
    messageBox.critical(0,"Redémarrage requis", "Le nouveau facteur d'échelle est de " + textScale.setNum (scale) + ", les changements d'échelles n'interviendront qu'après un redémarrage");
    messageBox.setFixedSize(500,200);
}

void MainWindow::on_Power_clicked()
{
    system("qdbus org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.logout 0 2 3");
}

void MainWindow::on_Reboot_clicked()
{
    system("qdbus org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.logout 0 1 3");
}

void MainWindow::on_Deconnection_clicked()
{
    system("qdbus org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.logout 0 0 3");
}

main. cpp

#include "mainwindow.h"
#include <QApplication>
#include <QtWidgets>
#include "ui_mainwindow.h"
#include "onhover.h"

int main(int argc, char *argv[])
{
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // DPI support
    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); //HiDPI pixmaps
    QApplication a(argc, argv);
    a.setWindowIcon(QIcon(":/images/Logo.png"));
    MainWindow w;
    w.show();
    connect( Ui::MainWindow::ConfigORCA, SIGNAL(hovered()), this, SLOT(do_something_when_button_hovered()) ); //this is in error
    return a.exec();
}

Я работаю в режиме доступа для людей с ограниченными возможностями. Звук, играющий для, поможет близким слепым. Остальные файлы (кроме измененных, написанных в up) присутствуют здесь: https://github.com/handyopensource/dvkbuntu-menu-acceuil

Мое приложение - очень простое меню с большой кнопкой.

Это не работает, как это сделать?

Спасибо.

1 Ответ

2 голосов
/ 15 марта 2020

Вы можете использовать фильтры событий , чтобы обнаружить зависание в виджете. Прочитайте все необходимое о системе событий Qt здесь .

Вот рабочий пример, который воспроизводит звук из файла ресурсов (прочитайте все, что вам нужно о системе ресурсов Qt здесь ), меняет фон надписи и печатает на экран (у меня было два варианта отладки):

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMediaPlayer>

namespace Ui
{
class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  explicit MainWindow(QWidget* parent = nullptr);
  ~MainWindow();

  virtual bool eventFilter(QObject* watched, QEvent* event);

private:
  Ui::MainWindow* ui;
  QMediaPlayer* player_ = nullptr;
};

#endif  // MAINWINDOW_H

mainwindow. cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QEvent>
#include <QMediaPlaylist>
#include <QUrl>

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
  Q_INIT_RESOURCE(qt_resources);
  ui->setupUi(this);
  ui->pushButton->installEventFilter(this);
  ui->label->setStyleSheet("background-color: red");
}

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

bool MainWindow::eventFilter(QObject* watched, QEvent* event)
{
  if (watched == ui->pushButton && event->type() == QEvent::HoverEnter)
  {
    qDebug() << "Start hover";
    ui->label->setStyleSheet("background-color: green");
    if (!player_)
    {
      QMediaPlaylist* playlist = new QMediaPlaylist();
      playlist->addMedia(QUrl("qrc:/push_button.mp3"));
      playlist->setPlaybackMode(QMediaPlaylist::Loop);

      player_ = new QMediaPlayer(this);
      player_->setPlaylist(playlist);
      player_->setVolume(50);
      player_->play();
    }
  }
  else if (watched == ui->pushButton && event->type() == QEvent::HoverLeave)
  {
    qDebug() << "End hover";
    ui->label->setStyleSheet("background-color: red");
    if (player_)
    {
      player_->stop();
      player_->deleteLater();
      player_ = nullptr;
    }
  }
  return QMainWindow::eventFilter(watched, event);
}

main

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

int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  MainWindow* mw = new MainWindow;
  mw->show();
  return app.exec();
}

Вы можете скачать рабочий проект (протестирован на Ubuntu 18.04 с Qt 5.9.5) здесь .

...