QInputDialog and QMessageBox - c++

I'm doing some preparation for an exam using Qt framework and I would like to know how to use QInputDialog and QMessageBox in a basic way (my exams are hand written coding)
The Qt API is really confusing to understand when it comes to using and it was fine for my projects because I could accomplish what I wanted in a really "hacky" way a my set book on the subject is very poorly laid out...
Let me get to the point, what would be a clean way of using QInputDialog and QMessageBox in this scenario:
#include <QApplication>
#include <QInputDialog>
#include <QDate>
#include <QMessageBox>
int computeAge(QDate id) {
int years = QDate::currentDate().year() - id.year();
int days = QDate::currentDate().daysTo(QDate
(QDate::currentDate().year(), id.month(), id.day()));
if(days > 0)
years--;
return years
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
/* I want my QInputDialog and MessageBox in here somewhere */
return a.exec();
}
For my QInputDialog I want the user to give their birth date (don't worry about input validation)
I want to use the QMessageBox to show the user's age
I just don't understand what parameters need to go into the QInputDialog and QMessageBox in a basic case like because there don't seem to be any examples out there.
How would I accomplish this?

You can do something like:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
bool ok;
// Ask for birth date as a string.
QString text = QInputDialog::getText(0, "Input dialog",
"Date of Birth:", QLineEdit::Normal,
"", &ok);
if (ok && !text.isEmpty()) {
QDate date = QDate::fromString(text);
int age = computeAge(date);
// Show the age.
QMessageBox::information (0, "The Age",
QString("The age is %1").arg(QString::number(age)));
}
[..]

Related

How to create QT Login Page bedore Mainwindow?

My Qt windows application is ready, but when the application opens, I want the login dialog to be opened, how can I do this? I'm new to Qt and C++. It would be great if it was descriptive.
You have many ways to achieve that... QDialog is a nice way. Here is a short sample using QInputDialog.
One solution could be to add this code in your main.cpp file, and to load the mainwindow only if the credentials are ok.
#include "gmainwindow.h"
#include <QApplication>
#include <QInputDialog>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GMainWindow w;
QString login = QInputDialog::getText(NULL, "Login","Name ?",QLineEdit::Normal);
if (login == "USER")
{
w.show();
}
else
{
//display an error message
return a.quit();
}
return a.exec();
}
Of course you may want to put an encrypted password and other things, but the idea will be more or less the same.

Why is QAudioRecorder not recording through the constructor?

header
#ifndef AUDIORECORD_H
#define AUDIORECORD_H
#include <QMediaRecorder>
#include <QAudioRecorder>
#include <QUrl>
class AudioRecorder : public QAudioRecorder
{
Q_OBJECT
public:
AudioRecorder(QObject * parent);
~AudioRecorder(){}
};
#endif // AUDIORECORD_H
source
#include "audiorecord.h"
#include<iostream>
using namespace std;
AudioRecorder::AudioRecorder(QObject * parent = 0)
{
this->setOutputLocation(QUrl::fromLocalFile("test.mp3"));
int x = 0;
while ( x > 10000)
{
this->record();
x++;
}
this->stop();
std::cout<<"\ndsffsdf\n";
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "audiorecord.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QObject p;
AudioRecorder obj(&p);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
This does not produce any error but it does not record also. I am not expecting any quality or full fledged recording.
I just want to see how this recorder works.
That test.mp3 is not getting saved.
What bare minimum can I add or subtract to it to make it record something and save?
Cause
What would be if I tell you 10 000 times: Go buy some milk, while firmly holding your hand, then just before I let you go to say: Ah, forget it? Would you be able to buy the milk?
You are doing the same with your code:
int x = 0;
while ( x > 10000)
{
this->record();
x++;
}
this->stop();
You are calling 10 000 times QAudioRecorder::record, but you do not let Qt get to the event loop and actualy execute your command. Then just before Qt gets to the event loop, you say: stop.
Solution
First of all, you do not need to subclass QAudioRecorder, because you do not add any new functionality to it. Just create an instance of the class and use it.
Second, record and stop are slots. Connect them to the clicked signal of the corresponding push buttons in you GUI, e.g.:
auto *audioRecorder = new QAudioRecorder(this);
...
connect(btnRecord, &QPushButton::clicked, audioRecorder, &QAudioRecorder::record);
connect(btnStop, &QPushButton::clicked, audioRecorder, &QAudioRecorder::stop);
Note: For more information, please take a look at the example from the documentation.

QCompleter::activated disconnected after losing and gaining focus

I found a strange case which I do not understand. Maybe it is a Qt bug, maybe I am doing something wrong.
A header:
// File mylineedit.h
#pragma once
#include <QLineEdit>
#include <QDebug>
class MyLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit MyLineEdit(QWidget *parent = nullptr) : QLineEdit(parent) { }
public slots:
void onCompleterActivated(const QString& text) { qDebug() << "MyLineEdit" << text; }
};
And the main source file:
// File main.cpp
#include <QApplication>
#include <QWidget>
#include <QStringListModel>
#include <QCompleter>
#include <QVBoxLayout>
#include "mylineedit.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
QLineEdit* lineEdit1 = new MyLineEdit();
QLineEdit* lineEdit2 = new MyLineEdit();
auto layout = new QVBoxLayout(&w);
layout->addWidget(lineEdit1);
layout->addWidget(lineEdit2);
lineEdit1->setCompleter(new QCompleter());
auto model = new QStringListModel(QStringList() << "A" << "B" << "C");
lineEdit1->completer()->setModel(model);
QObject::connect(lineEdit1->completer(), SIGNAL(activated(QString)), lineEdit1, SLOT(onCompleterActivated(QString)));
w.show();
return a.exec();
}
Once you run this, you can get a completer with values "A", "B", "C" in the first line edit. When you select any of these values, it will print the message to the console. This is correct. But then change focus to the other line edit and then back. Try picking "A", "B", "C" again. No message is printed out, the signal/slot seems disconnected. Any ideas?
Tested with MinGW 5.3.0 and MSVC 2015 using with Qt 5.9.2.
I modified your sample slightly and tried to reproduce the behavior you described but I couldn't:
#include <QtWidgets>
int main(int argc, char **argv)
{
qDebug() << "Qt Version: " << QT_VERSION_STR;
// main application
QApplication app(argc, argv);
// setup GUI
QWidget qWin;
QVBoxLayout qVBox;
QLineEdit qEdit1;
qVBox.addWidget(&qEdit1);
QCompleter qCompl1;
QStringListModel qComplModel(QStringList() << "A" << "B" << "C");
qCompl1.setModel(&qComplModel);
qEdit1.setCompleter(&qCompl1);
QLineEdit qEdit2;
qVBox.addWidget(&qEdit2);
qWin.setLayout(&qVBox);
qWin.show();
// install signal handlers
QObject::connect(&qCompl1,
static_cast<void(QCompleter::*)(const QString&)>(
&QCompleter::activated),
[](const QString &text)
{
qDebug() << "Activated: " << text;
});
// run-time loop
return app.exec();
}
The significant differences in my sample:
I used Qt5 style signal handlers (as I'm used to).
I didn't new the Qt widgets (as I'm used to when I write minimal samples).
For me, it's hard to believe that one of these changes makes your described issue unbroken.
I compiled and tested with VS2013, Qt 5.9.2 on Windows 10 (64 bit):
I did the following interactions:
click in qEdit1
type A and click on item A in the popup menu
Output:
Activated: "A"
I continued with:
click in qEdit2
type B
click in qEdit1
erase text, type B, and click on item B in the popup menu
Output:
Activated: "B"
It works like expected.
After some conversation, I had a look at woboq.org in the source code of QLineEdit:
The interesting part is in QLineEdit::focusOutEvent:
if (d->control->completer()) {
QObject::disconnect(d->control->completer(), 0, this, 0);
}
If I read this right, all signal handlers of QLineEdit (emitted by the set completer) are disconnected. I believe this is the reason for the observed issue. (Therefore, it works for lambdas and methods of other classes.)

c++ gui button output

i have a few questions regarding the gui of cplusplus using Qt creator
well i output an array using a forloop when user's choice is for example "1"
so in qt i created a button for that and i linked it with another window
so when i press on the button it opens another window
now i want to add the output of the forloop into this window
should i include iostream in the new window's .cpp file?
or what should i enter exactly?
in the mainwindow.cpp file here is the code i used to open a new window
void MainWindow::on_pushButton_clicked()
{
movies movies;
movies.setModal(true);
movies.exec();
}
thanks.
You should add a QTextEdit to your window (can be done via Qdesigner). And give this object a name e.g. Textout. Then in the code you should get a pointer to this object through your ui object. And you can use one of many methods to set the text of this object. setText is one option
ui->Textout->setText(Your_output_as_qstring)
Your can use QTextStream to format your text if necessary. Formating can be done with QString as well.
example:
#include <sstream>
#include <QLabel>
#include <QApplication>
int main(int argc, char *argv[])
{
std::stringstream ss;
for (auto s: {"first line", "second line"})
ss << s << std::endl;
QApplication a(argc, argv);
QLabel l;
l.setText(ss.str().c_str());
l.show();
return a.exec();
}

Multiline QInputDialog prompt

I am currently using something like this:
QString text = QInputDialog::getText(this, tr("title"),"Hello World !! What goes in here", QLineEdit::Normal, QString(""), &ok);
Now I want the text in the Dialog
"Hello World !! What goes in here"
to be spread over two lines. like this
Hello World !!
What goes in here
Any suggestions on what I could do ??
Simply insert a line break:
"Hello World!!\nWhat goes in here"
The complete compileable example shows why sometimes using an application framework isn't that bad of an idea. It's no longer than a comparable command-line variant would be, assuming that you had a proper, Unicode-based standard library to start with.
#include <QApplication>
#include <QInputDialog>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QInputDialog::getText(nullptr, "Title", "Hello World !!\nWhat goes in here");
return 0;
}