I need to play a sound when a button is clicked, I have this:
Phonon::MediaObject *clickObject = new Phonon::MediaObject(this);
clickObject->setCurrentSource(Phonon::MediaSource("Click/sound.wav");
Phonon::AudioOutput *clickOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
Phonon::createPath(clickObject, clickOutput);
and
void MainWindow::on_pushButton_clicked()
{
clickObject->play();
}
but no sound is played?
Where am I wrong?
Thanks.
EDIT: It works now, it was the wrong path.
Probably the file path "Click/sound.wav" doesn't point where you think it points.
Try this before calling the setCurrentSource()-function:
bool exists = QFile::exists("Click/sound.wav");
If the Click directory is supposed to be in the same directory as your exe, create the path like this:
QString filePath = QCoreApplication::applicationDirPath() + "/Click/sound.wav";
clickObject->setCurrentSource(Phonon::MediaSource(filePath));
And I would suggest using Qt resource system. Then you would point to the sound file like this:
clickObject->setCurrentSource(Phonon::MediaSource(":/Click/sound.wav"));
You should at least connect the signal stateChanged(Phonon::State, Phonon::State) from your MediaObject object to a custom slot to detect errors: if the state changes to Phonon::ErrorState the reason of the error might be accessible through QMediaObject::errorString().
Related
I have a problem with the QFileDialog class, namely with the setDirectory() and directory() methods. I need to make it so that after opening a file, my program remembers the directory in which the selected file is stored, and the next time QFileDialog is called, it automatically opens the directory that was used last. Here is a snippet of my code:
static QString _st_doc_last_directory;
void MainWindow::open()
{
if (!fileDialog)
{ fileDialog = new QFileDialog(this);
}
if (!_st_doc_last_directory.isEmpty()) fileDialog->setDirectory(_st_doc_last_directory);
QString fileName = fileDialog->getOpenFileName(this, tr("Open Document"), ".", tr("Compressed CAD Models (*.data)"));
if (!fileName.isEmpty())
{ _st_doc_last_directory = fileDialog->directory().dirName();
}
}
The crux of my problem is that when the setDirectory() or directory() method is called, my program crashes with a
"Segmentation fault"
message. How can I fix it, please advise. Thanks in advance.
Whenever you start this method, you have this as the start window: ".". (admittedly I don't know what's going on internally, but I think this leads to this problem).
You can query beforehand whether your defined string is empty. if so you set a path, otherwise you store one in your string. If you don't want to do this from the beginning every time you start the program, you can also use QSettings. This saves you the path in the registry (ie if you use windows).
With QFileInfo you can easily get the path
void MainWindow::open()
{
if(_st_doc_last_directory.isEmpty())
_st_doc_last_directory = QDir::homePath();
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Document"), _st_doc_last_directory, tr("Compressed CAD Models (*.data)"));
QFileInfo info(fileName);
if(!fileName.isEmpty())
_st_doc_last_directory = info.absolutePath();
}
I want to use QAudioRecorder to record an audio and save as a file and display the filepath to the user. I had tried using the the example from Qt but there's no feed on the buffer value when I tested it on Android. It works on my Desktop though. Below are part of my codes:
AudioRecord::AudioRecord(QWidget *parent)
{
audioRecorder = new QAudioRecorder(this);
probe = new QAudioProbe;
connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)),
this, SLOT(processBuffer(QAudioBuffer)));
probe->setSource(audioRecorder);
}
void AudioRecord::processBuffer(const QAudioBuffer& buffer)
{
qDebug()<<"Testing Successful";
}
The processBuffer function does not seems to be called. What should I do to get the buffer value work? Is there any other way around?
Thanks!
I'm new to QT. Currently in my project I implemented QFileDialog.
In my usecase : whenever user choose a text file, it executes functionA. However, I found that if I click cancel in the fileDialog, functionA will still be executed.
This is my code snipplet:
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
"/home",
tr("Text File (*.txt"));
// I want something like following :
if(QFileDialog.isOkButtonClicked)
{
// execute functionsA
}
I looked into QFileDialog documentation and nothing similiar.
Is it possible to achieve this or is there any other solution ? thanks.
thanks to AlexanderVX
the solution is simple :
if(!fileName.isEmpty()&& !fileName.isNull()){
// functionA
}
i am wondering if its possible to solve this problem.
Ive got qt application and if user tick the checkbox, i want this application to launch on startup of operating system.
Ive already googled, and ive come up with this solution>
my QT application needs admin privileges in order to modify registry, so
create manifest file ( <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>)
2.apply this command
mt -manifest manifestfile -outputresource:binfile.exe;1
3.use this piece of code in QT to modify registry
void MainWindow::set_on_startup() {
QSettings settings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
if (ui->checkBox->checkState()) {
QString value = QCoreApplication::applicationFilePath(); //get absolute path of running exe
QString apostroph = "\"";
#ifdef DEBUG
ui->textEdit->append(QCoreApplication::applicationFilePath ());
#endif
value.replace("/","\\");
value = apostroph + value + apostroph + " --argument";
#ifdef DEBUG
ui->textEdit->append(value);
#endif
//write value to the register
settings.setValue("name", value);
}
else {
settings.remove("name");
}
}
So, this looks good right ?
BUT... application with default admin priveleges cant be launched on startup of operating system, BUT application without admin priveleges cant modify registry. So , there is one solution - tell a user, that if he wants to set this "startup" option, he first needs to start application as admin, then the application will be able to modify registry, and default privileges will remain "asInvoker", but this seems really impractical and i think that users will be discouraged by this.
So, how to solve this problem ? how other applications solve this problem ?
You won't need admiministrator privileges if you use following key:
QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
Notice
HKEY_CURRENT_USER
instead of using
HKEY_LOCAL_MACHINE
My 2 cents! : )
Why not simply put the app shortcut in "Startup" folder.
Qt provides a cross-platform way of determining the paths to many default system directories using the QDesktopServices class.
(Source: Thanks to Dave Mateer for his answer to this question.)
The method is:
QDesktopServices::storageLocation(QDesktopServices::ApplicationsLocation)
This gives (on my Win 7):
C:\Users\user_name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
and all we need is:
C:\Users\user_name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Simple!
I use this without any hassle of UAC or any kind of rights problem in most of my apps.
This may not be the best way... but it is certainly an easy way.
(Please pitch in thoughts/comments if this approach has any big disadvantages.)
Update:
To create the short-cut for the application in startup folder, use this code:
QFileInfo fileInfo(QCoreApplication::applicationFilePath());
QFile::link(QCoreApplication::applicationFilePath(), QDesktopServices::storageLocation(QDesktopServices::ApplicationsLocation) + QDir::separator() + "Startup" + QDir::separator() + fileInfo.completeBaseName() + ".lnk");
I hope this helps! : )
Include this header QSettings
#include <QSettings>
And add this into your code.
QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
QSettings::NativeFormat);
settings.setValue("YourApplicationName",
QCoreApplication::applicationFilePath().replace('/', '\\'));
For everybody who are trying to solve the problem, this is the 100% working solution:
How can I ask the user for elevated permissions at runtime?
create app1.exe
create app2.exe with admin priveleges - tutorial is in the first post (manifest file, mt.exe, etc..)
when user tick the checkbox in app1.exe, i call the the app2.exe (for example with no arguments) - you can find all function for this # the link ive just posted above
// well, in fact, you dont have to use the function from the example above:
i find this call much better
QObject *parent = new QObject();
QString program = AppToExec; //"/path/to/the/app2.exe"
QStringList arguments ;
arguments << ""; //just in case we want arguments
QProcess *myProcess = new QProcess(parent);
myProcess->start(program);
app2.exe, for example
QApplication a(argc, argv);
MainWindow w;
// w.show();
if (argc == 1) {
w.test();
a.quit();
}
problem solved.
Using this link
create stratup app and code:
void make_startup_app(){
QString appName = "app.exe";
QString appNameLink = appName+".lnk";
QFile::link(appName, appNameLink);
QString userName = QDir::home().dirName();
QString dir_startup = "C:/Users/" + userName +
"/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/"+ appNameLink;
QFile::copy(appNameLink, dir_startup);
}
I'm having a bit of trouble with my function for displaying pdf's with the poppler library. The code below is the function in which the problem occurs.
const QString &file is the path to the file
int page is the page on which it has to open
When i set file to a real path (e.g. "/Users/User/Documents/xxx.pdf"), it is no problem to open it. But when i give the path to a qrc file (":/files/xxx.pdf"), it won't work. I want to use it for displaying a user manual for instance, within the application.
I've also tried first making a QFile out of it, opening it and doing readAll, then loading the QByteArray received by doingPoppler::Document::loadFromData(the qbytearray), but it errors already when opening the QFile in ReadOnly mode.
void class::setPdf(const QString &file, int page)
{
Poppler::Document *doc = Poppler::Document::load(file);
if (!doc) {
QMessageBox msgbox(QMessageBox::Critical, tr("Open Error"), tr("Please check preferences: cannot open:\n") + file,
QMessageBox::Ok, this);
msgbox.exec();
}
else{ /*Code for displaying the pdf, which works fine*/
}
}
I hope you can help me,
greetings,
Matt
I've also tried first making a QFile
out of it, opening it and doing
readAll, then loading the QByteArray
received by
doingPoppler::Document::loadFromData(the
qbytearray), but it errors already
when opening the QFile in ReadOnly
mode.
QFile f;
f.setFileName(":/skin/AppIcon16.png");
f.open(QIODevice::ReadOnly);
QByteArray r=f.readAll();
Perfectly reads all data from the resource, have checked it. So i suggest you did something wrong when tried that. Maybe path errors, maybe something else...