I'm trying call a Qt Mainwindow function in my main function but unfortunately it does not work
some info: I've written a simple log in application. here's the code for it:
void MainWindow::on_pushButton_Login_clicked()
{
QString username = ui->lineEdit_username->text();
QString password = ui->lineEdit_password->text();
if(username == "test" && password == "test")
{
QMessageBox::information(this,"Login", "Username and password is
correct");
}
else
{
QMessageBox::warning(this,"Login", "Username and Password is not
correct");
}
}
I also have a piece of code for saving the content of a batch file into a vector.
and in that code I have a find function, to look for a certain word.
what I'm trying to achieve here exactly is 1.save the contents of the batch to my vector, then have the find function look for that certain word in that vector and then when this word is found, prompt the user to enter username and password (which is done through my log in application)
Now here's where my problem is, I have all the code, separately but I don't know how to put it together, I'm not a c++ programmer, in fact I'm a complete noob. my boss just asked me to get this done, and I'm struggling :c
Here's the code for populating my vector with the contents of the batch file
int main()
{
// VARIABLES
// file path, pointer
const char * filePath = "C:/Users/Name/Downloads/test.bat";
// single line
std::string line;
// vector
std::vector<std::string> my_vec;
// filestream, reading
//std::ifstream myfile("batch.bat");
std::ifstream myfile(filePath);
// Test to open file
if (!myfile)
{
std::cout << "Error opening file" << std::endl;
exit(1);
}
else
{
std::cout << "File opened successfully (for reading)" << std::endl;
}
// Read from file and put into vector
while (myfile) // while we are reading the file
{
getline(myfile, line);
my_vec.push_back(line);
}
//my find function
std::vector<std::string>::iterator i;
i = std::find(my_vec.begin(),my_vec.end(),"batch");
if (i != my_vec.end())
/**** here is where id like to call my clicked function ****/
/* tried putting in "void MainWindow::on_pushButton_Login_clicked()" but it
here's what I got */
1. error: undefined reference to `qMain(int, char**)'
and collect2.exe:-1: error: error: ld returned 1 exit status
else
std::cout<<"No result found" << std::endl;
// Close filestream
myfile.close();
return 0;
}
I truly apologize if this is too specific or an extremely dumb question, but I just needed help and I couldn't find anything on such a specific question, also everything that could help, is for people who actually know what they're doing with c++
I'd appreciate any contribution!
Bearded beaver: My MainWindow class is defined in my mainwindow.H header file
which I included in my main.cpp file
heres the code in that Mainwindow.h file
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void on_pushButton_Login_clicked();
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
and here is what I entered in my Find function from above
std::vector<std::string>::iterator i;
i = std::find(my_vec.begin(),my_vec.end(),"much");
if (i != my_vec.end())
MainWindow.on_pushButton_Login_clicked();
else
std::cout<<"No result found" << std::endl;
and this is the error that I get
main.cpp:101: error: expected unqualified-id before '.' token
MainWindow.on_pushButton_Login_clicked();
^
thanks for taking the time!
I basically did something really stupid by altering the main.cpp file (in Qt Widgets application) and removing the default main function which looked like this
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
In that the object name was declared, I needed it to to call my function which was in that MainWindow class. like so:
w.on_pushButton_Login_clicked();
unfortunately though, my find function does not work.
I wanted to have a conditional statement that calls upon my function if a certain string element in my vector is found using:
if (std::find(my_vec.begin(),my_vec.end(),much) != my_vec.end() ) //or "much"
w.on_pushButton_Login_clicked();
else
std::cout<<"No result found" << std::endl;
I get no errors, it just prompts me to the log in application regardless of if element was found.
I don't know why this happens, but if I found out, I will edit this answer ^^ thank you guys for taking the time, apologize in advance if i used wrong terminology/wording.
Related
I'm new to implementing Threads in QT and even after reading the Documentation several times and watching Videos, I get some Error which not even Google can help me with.
thread.cpp:14: error: C2440: "Initialisierung": "QFuture" kann nicht in "QFuture" konvertiert werden
Error Codes are in German, tried to change QT Language, but didn't change the Language of the Errors. I can translate them if needed.
It seems the Error happens in this QFuture<int> future = QtConcurrent::run(&Thread::GenerateTable); command, even thought I wrote it 1:1 like from the QT Documentation.
Here is the Code I want to put in a Thread, as you can see it's writing a bit bunch of Numbers into a File, which takes around a Minute.
Thread.h
#ifndef THREAD_H
#define THREAD_H
#include <QObject>
#include <QFuture>
#include <QtConcurrent/QtConcurrent>
class Thread : public QObject
{
Q_OBJECT
public:
explicit Thread(QObject *parent = nullptr);
static bool start();
private:
int GenerateTable();
};
#endif // THREAD_H
Thread.cpp
#include "thread.h"
Thread::Thread(QObject *parent) : QObject(parent)
{
}
bool Thread::start()
{
QFuture<int> future = QtConcurrent::run(&Thread::GenerateTable);
if (future.result() == 0){
return true;
}
else
return false;
}
int Thread::GenerateTable(){
QString Path = QDir::currentPath();
QFile file(Path + "/Table.csv");
if (!file.open(QFile::WriteOnly | QFile::Text)){
return -1;
}
else{
QTextStream stream(&file);
constexpr uint64_t upper = 10'000'000;
QVector<uint64_t> rando(upper);
std::iota(rando.begin(), rando.end(), 1);
std::shuffle(rando.begin(), rando.end(),
std::mt19937(std::random_device{}()));
for (uint32_t i = 0; i < 10'000'000; ++i) {
stream << rando[i] << ',' << '\n';
}
return 0;
}
}
Thread::GenerateTable() is a member function. It needs an object to work on. You are calling it (er .. passing it to QtConcurrent::run()) from the (static) Thread::start() and there's no Thread object to speak of.
Although you've tagged Qt6, I'll point at the Qt5 documentation for calling member functions: you can pass an object (pointer) which you'll need to allocate from somewhere.
I am working on a Save dialog for my qt app. Everything works, but if no file extension is added behind the filename, it won't automatically be saved with the file extension although the filter is selected.
I know i need to set a defaultsuffix option, but even if i do, then it still won't add the extension automatically if its not given.
I found several other similar questions, where i read it works in windows but it could fail on linux distro's. If so, is there a simple workaround? Because right now, i don't have a working solution...
void MainWindow::on_actionSave_Chart_As_triggered()
{
QFileDialog *fileDialog = new QFileDialog;
fileDialog->setDefaultSuffix("files (*);;AstroQt aqt (*.aqt)");
QString fileName = fileDialog->getSaveFileName(this, "Save Radix", ui->label_2->text() +".aqt", "AstroQT(*.aqt)");
qDebug() << " save file name " << fileName << endl;
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
return;
}
setWindowTitle(fileName);
QTextStream out(&file);
QString text = "text that will be saved...";
out << text;
file.close();
}
Edit: After trying multiple solutions, none seemed to work. But it should have, i guess. Why else is there a aftersuffix function...? For now i solved it doing it manually. But i'm not happy with it, there should be a better solution/explanation.
// add extension if none is found.
if(!fileName.endsWith(".aqt"))
fileName.append(".aqt");
If you use the static method getSaveFileName things seems to work correctly:
#include <QFileDialog>
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QString fileName = QFileDialog::getSaveFileName(
nullptr, QObject::tr("Save File"),
"teste.aqt",
QObject::tr("AstroQt (*.aqt)"));
qDebug() << " save file name " << fileName << endl;
return app.exec();
}
I get the correct file name with the extension, if I type something without the extension.
If you take a look at QFileDialog documentation, you will see that getSaveFileName() is an static function. Because of this, there is no way for this method to access a member of the instance of the class that makes use of setDefaultSuffix(). So whatever you set in fileDialog->setDefaultSuffix(...) has nothing to do with what the getSaveFileName() function does.
In ordertTo make it work, you have to run the dialog directly from the instance. You should do something like this:
QFileDialog fileDialog(this, "Choose file to save");
fileDialog.setDefaultSuffix("json");
fileDialog.setNameFilter("json-files (*.json)");
fileDialog.exec();
QFile f(fileDialog.selectedFiles().first());
QFileInfo fileInfo(f);
QString FILE_NAME(fileInfo.fileName());
I have been all day long googling for a solution and changing my code, but no luck.
Basically, I have added translation to my app. It is working fine except here:
QString MainWindow::getMessage(Messages msg) {
static const char* const messages[] = {
QT_TR_NOOP("Setting power on"),
QT_TR_NOOP("Reading ID..."),
QT_TR_NOOP("Programming..."),
QT_TR_NOOP("Setting write-protect"),
QT_TR_NOOP("Finished ok"),
QT_TR_NOOP("PROGRAMMED OK"),
QT_TR_NOOP("ERROR!"),
QT_TR_NOOP("OK"),
QT_TR_NOOP("The programmer is not connected.\nPlease check the connection."),
QT_TR_NOOP("Disconnect the board, it is in short!!"),
QT_TR_NOOP("ERROR: Supply voltage too low (1 Volt is required, Measured: 0.0 Volt)."),
QT_TR_NOOP("Board is already programmed and write protected."),
QT_TR_NOOP("Check device connection or there is short."),
QT_TR_NOOP("Unknown error.")
};
return tr(messages[msg]);
}
However, I don't get the translation. The files for translation seems to be ok, the UI translations are applied fine.
I also tried this:
static const char* const messages[] = {
QT_TRANSLATE_NOOP("test", "Setting power on"),
QT_TRANSLATE_NOOP("test", "Reading ID..."),
QT_TRANSLATE_NOOP("test", "Programming..."),
QT_TRANSLATE_NOOP("test", "Setting write-protect"),
QT_TRANSLATE_NOOP("test", "Finished ok"),
QT_TRANSLATE_NOOP("test", "PROGRAMMED OK"),
QT_TRANSLATE_NOOP("test", "ERROR!"),
QT_TRANSLATE_NOOP("test", "OK"),
QT_TRANSLATE_NOOP("test", "The programmer is not connected.\nPlease check the connection."),
QT_TRANSLATE_NOOP("test", "Disconnect the board, it is in short!!"),
QT_TRANSLATE_NOOP("test", "ERROR: Supply voltage too low (1 Volt is required, Measured: 0.0 Volt)."),
QT_TRANSLATE_NOOP("test", "Board is already programmed and write protected."),
QT_TRANSLATE_NOOP("test", "Check device connection or there is short."),
QT_TRANSLATE_NOOP("test", "Unknown error.")
};
Then, I have a method to get the message:
QString MainWindow::getMessage(Messages msg) {
return qApp->translate("test", messages[msg]);
}
But it doesn't work either.
Any tips or suggestions?
I have found the real issue here.
Usually translators are installed at main.cpp, so the translator object remains in memory.
However, in my case, I was switching the translator after the user changes the language at settings dialog, using a local variable but void QCoreApplication::installTranslator ( QTranslator * translationFile ) [static] needs a pointer. That local variable is removed as soon as the function exits.
So, I declared a QTranslator object on my class, so it keeps in memory.
Maybe not applicable in this situation, but often people forget to place the Q_OBJECT macro in the class declaration. Resulting in (amongst others) tr() not working.
I was preparing a simpler source to upload here but now it is working fine! I rebooted my PC yesterday, you know, sometimes a reboot fixes everything (?).
Anyway, here is some source as it was requested. And by the way, I'm doing the translation on the fly, and by letting the user to choose the language (not by detecting locales):
This is main.cpp (nothing was added by me):
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
This is mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QTranslator>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QDir d(":/translations/");
QStringList files = d.entryList(QStringList("*.qm"));
qDebug("There are %d files for translation", files.count());
// Now let's fill the combobox
this->ui->comboBox->clear();
for (int i = 0; i < files.count(); ++i) {
QTranslator translator;
translator.load(files[i], ":/translations/");
QString language = translator.translate("MainWindow",
"English");
this->ui->comboBox->addItem(language);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_comboBox_currentIndexChanged(int index)
{
// Now, based on the new itemindex, let's change the translator
QString selectedLang = this->ui->comboBox->itemText(index);
QString language;
QDir d(":/translations/");
QStringList files = d.entryList(QStringList("*.qm"));
for (int i = 0; i < files.count(); ++i) {
QTranslator translator;
translator.load(files[i], ":/translations/");
language = translator.translate("MainWindow",
"English");
if (language == selectedLang) {
if (!qApp->installTranslator(&translator)) {
qDebug("ERROR INSTALLING TRANSLATOR !!!");
}
this->uiTranslate();
break;
}
}
}
/// This function translates all the UI texts:
void MainWindow::uiTranslate(void) {
this->setWindowTitle(tr("MainWindow"));
// Just for testing, also show all the messages
for (int i = 0; i < MSG_LAST; ++i) {
this->ui->textBrowser->append(this->getMessage((Messages)i));
}
}
QString MainWindow::getMessage(Messages idx) {
static const char* const messagesText[MSG_LAST] = {
QT_TR_NOOP("Hello!"),
QT_TR_NOOP("Bye bye"),
QT_TR_NOOP("Nice to meet you")
};
return (tr(messagesText[idx]));
}
in this test app, the UI just has a combobox and a text browser.
The combobox is filled with the languages included on the resource file.
When I change the combobox, the mainwindow title is changed and the messages are printed in the right language.
Thanks anyway!
Best regards,
I am trying to instantiate a printer without using QPrintDialog as our GUI is QML where QPrintDialog does not exist (we are creating a printer selection dialog in QML). I am calling two invokable C++ functions 1) one function retrieves a list of valid printers and passes that back to QML, and 2) second function instantiate a printer name that was selected by the user in QML and then prints to a painter. I am using Ubuntu Linux (32) with Qt5.4.0. One interesting issue I uncovered is that when I use QPrinterInfo::availablePrinterNames() a valid list of printer names is found. When I get a list of QPrinterInfo object via using static function QPrinterInfo::availablePrinters(), then traverse the list and display the names in printerName, an empty string is returned. The documentation says that this should be a unique ID for the printer, not an empty string?????
Here's is a extract which demonstrates the issue:
#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrinterInfo>
#include <QDebug>
#include <QList>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "Printer names via availablePrinterNames method";
QStringList name_list = QPrinterInfo::availablePrinterNames();
foreach ( QString name, name_list)
qDebug() << name;
qDebug() << "\nPrinter names via availablePrinters method";
QList<QPrinterInfo> info_list = QPrinterInfo::availablePrinters();
foreach ( QPrinterInfo info, info_list )
qDebug() << info.printerName();
return a.exec();
}
I have not tried this with earlier versions of QT or the Windows version. Does anyone have any hints?
Thanks
In short: The reason for the issue is that CUPS supports driverless printers (info), and Qt does not.
Qt uses CUPS API to return the list of printers in system (availablePrinterNames) without checking, but when it constructs QPrinterInfo, it checks if the printer has a PPD driver. If not, the printer is considered invalid, and Qt returns empty name for it.
Please try this, it worked for me. First you should add windowsprintersupport.dll to your project.
int count = 0;
QList<QPrinterInfo> info_list = QPrinterInfo::availablePrinters();
foreach ( QPrinterInfo info, info_list )
{
count++;
qDebug()<< "Printer_"<< count<< ": " << info.printerName() << "State: " << info.state();
if(info.printerName() == "YOUR_PRINTER_NAME")
{
if (info.state() == 0)
qDebug()<< "Printer Idle";
else if (info.state() == 1)
qDebug()<< "Printer Active";
else if (info.state() == 2)
qDebug()<< "Printer Aborted";
else if (info.state() == 3)
qDebug()<< "Printer Error";
else
qDebug()<< "Printer Undefined Error";
}
}
I have a Qt GUI application running on Windows that allows command-line options to be passed and under some circumstances I want to output a message to the console and then quit, for example:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if (someCommandLineParam)
{
std::cout << "Hello, world!";
return 0;
}
MainWindow w;
w.show();
return a.exec();
}
However, the console messages do not appear when I run the app from a command-prompt. Does anyone know how I can get this to work?
Windows does not really support dual mode applications.
To see console output you need to create a console application
CONFIG += console
However, if you double click on the program to start the GUI mode version then you will get a console window appearing, which is probably not what you want. To prevent the console window appearing you have to create a GUI mode application in which case you get no output in the console.
One idea may be to create a second small application which is a console application and provides the output. This can call the second one to do the work.
Or you could put all the functionality in a DLL then create two versions of the .exe file which have very simple main functions which call into the DLL. One is for the GUI and one is for the console.
Add:
#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
#endif
at the top of main(). This will enable output to the console only if the program is started in a console, and won't pop up a console window in other situations. If you want to create a console window to display messages when you run the app outside a console you can change the condition to:
if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())
void Console()
{
AllocConsole();
FILE *pFileCon = NULL;
pFileCon = freopen("CONOUT$", "w", stdout);
COORD coordInfo;
coordInfo.X = 130;
coordInfo.Y = 9000;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coordInfo);
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),ENABLE_QUICK_EDIT_MODE| ENABLE_EXTENDED_FLAGS);
}
int main(int argc, char *argv[])
{
Console();
std::cout<<"start##";
qDebug()<<"start!";
You can't use std::cout as others have said,my way is perfect even for some code can't include "qdebug" !
So many answers to this topic. 0.0
So I tried it with Qt5.x from Win7 to Win10. It took me some hours to have a good working solution which doesn't produce any problems somewhere in the chain:
#include "mainwindow.h"
#include <QApplication>
#include <windows.h>
#include <stdio.h>
#include <iostream>
//
// Add to project file:
// CONFIG += console
//
int main( int argc, char *argv[] )
{
if( argc < 2 )
{
#if defined( Q_OS_WIN )
::ShowWindow( ::GetConsoleWindow(), SW_HIDE ); //hide console window
#endif
QApplication a( argc, argv );
MainWindow *w = new MainWindow;
w->show();
int e = a.exec();
delete w; //needed to execute deconstructor
exit( e ); //needed to exit the hidden console
return e;
}
else
{
QCoreApplication a( argc, argv );
std::string g;
std::cout << "Enter name: ";
std::cin >> g;
std::cout << "Name is: " << g << std::endl;
exit( 0 );
return a.exec();
}
}
I tried it also without the "CONFIG += console", but then you need to redirect the streams and create the console on your own:
#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
freopen("CONIN$", "r", stdin);
}
#endif
BUT this only works if you start it through a debugger, otherwise all inputs are directed towards the system too. Means, if you type a name via std::cin the system tries to execute the name as a command. (very strange)
Two other warnings to this attempt would be, that you can't use ::FreeConsole() it won't close it and if you start it through a console the app won't close.
Last there is a Qt help section in QApplication to this topic. I tried the example there with an application and it doesn't work for the GUI, it stucked somewhere in an endless loop and the GUI won't be rendered or it simply crashes:
QCoreApplication* createApplication(int &argc, char *argv[])
{
for (int i = 1; i < argc; ++i)
if (!qstrcmp(argv[i], "-no-gui"))
return new QCoreApplication(argc, argv);
return new QApplication(argc, argv);
}
int main(int argc, char* argv[])
{
QScopedPointer<QCoreApplication> app(createApplication(argc, argv));
if (qobject_cast<QApplication *>(app.data())) {
// start GUI version...
} else {
// start non-GUI version...
}
return app->exec();
}
So if you are using Windows and Qt simply use the console option, hide the console if you need the GUI and close it via exit.
No way to output a message to console when using QT += gui.
fprintf(stderr, ...) also can't print output.
Use QMessageBox instead to show the message.
Oh you can Output a message when using QT += gui and CONFIG += console.
You need printf("foo bar") but cout << "foo bar" doesn't works
Something you may want to investigate, at least for windows, is the AllocConsole() function in the windows api. It calls GetStdHandle a few times to redirect stdout, stderr, etc. (A quick test shows this doesn't entirely do what we want it to do. You do get a console window opened alongside your other Qt stuff, but you can't output to it. Presumably, because the console window is open, there is some way to access it, get a handle to it, or access and manipulate it somehow. Here's the MSDN documentation for those interested in figuring this out:
AllocConsole():
http://msdn.microsoft.com/en-us/library/windows/desktop/ms681944%28v=vs.85%29.aspx
GetStdHandle(...):
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231%28v=vs.85%29.aspx
(I'd add this as a comment, but the rules prevent me from doing so...)
I used this header below for my projects. Hope it helps.
#ifndef __DEBUG__H
#define __DEBUG__H
#include <QtGui>
static void myMessageOutput(bool debug, QtMsgType type, const QString & msg) {
if (!debug) return;
QDateTime dateTime = QDateTime::currentDateTime();
QString dateString = dateTime.toString("yyyy.MM.dd hh:mm:ss:zzz");
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s\n", msg.toAscii().data());
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg.toAscii().data());
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg.toAscii().data());
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s\n", msg.toAscii().data());
abort();
}
}
#endif
PS: you could add dateString to output if you want in future.
First of all, why would you need to output to console in a release mode build? Nobody will think to look there when there's a gui...
Second, qDebug is fancy :)
Third, you can try adding console to your .pro's CONFIG, it might work.
In your .pro add
CONFIG += console
It may have been an oversight of other answers, or perhaps it is a requirement of the user to indeed need console output, but the obvious answer to me is to create a secondary window that can be shown or hidden (with a checkbox or button) that shows all messages by appending lines of text to a text box widget and use that as a console?
The benefits of such a solution are:
A simple solution (providing all it displays is a simple log).
The ability to dock the 'console' widget onto the main application window. (In Qt, anyhow).
The ability to create many consoles (if more than 1 thread, etc).
A pretty easy change from local console output to sending log over network to a client.
Hope this gives you food for thought, although I am not in any way yet qualified to postulate on how you should do this, I can imagine it is something very achievable by any one of us with a little searching / reading!
Make sure Qt5Core.dll is in the same directory with your application executable.
I had a similar issue in Qt5 with a console application:
if I start the application from Qt Creator, the output text is visible,
if I open cmd.exe and start the same application there, no output is visible.
Very strange!
I solved it by copying Qt5Core.dll to the directory with the application executable.
Here is my tiny console application:
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
int x=343;
QString str("Hello World");
qDebug()<< str << x<<"lalalaa";
QTextStream out(stdout);
out << "aldfjals alsdfajs...";
}
I also played with this, discovering that redirecting output worked, but I never saw output to the console window, which is present for every windows application. This is my solution so far, until I find a Qt replacement for ShowWindow and GetConsoleWindow.
Run this from a command prompt without parameters - get the window. Run from command prompt with parameters (eg. cmd aaa bbb ccc) - you get the text output on the command prompt window - just as you would expect for any Windows console app.
Please excuse the lame example - it represents about 30 minutes of tinkering.
#include "mainwindow.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QApplication>
#include <QWidget>
#include <windows.h>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
if (argc > 1) {
// User has specified command-line arguments
QCoreApplication a(argc, argv);
QTextStream out(stdout);
int i;
ShowWindow (GetConsoleWindow(),SW_NORMAL);
for (i=1; i<argc; i++)
out << i << ':' << argv [i] << endl;
out << endl << "Hello, World" << endl;
out << "Application Directory Path:" << a.applicationDirPath() << endl;
out << "Application File Path:" << a.applicationFilePath() << endl;
MessageBox (0,(LPCWSTR)"Continue?",(LPCWSTR)"Silly Question",MB_YESNO);
return 0;
} else {
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle("Simple example");
w.show();
return a.exec();
}
}
After a rather long struggle with exactly the same problem I found that simply
CONFIG += console
really does the trick. It won't work until you explicitly tell QtCreator to execute qmake on the project (right click on project) AND change something inside the source file, then rebuild. Otherwise compilation is skipped and you still won't see the output on the command line.
Now my program works in both GUI and cmd line mode.
One solution is to run powershell and redirect the output to whatever stream you want.
Below is an example of running powershell from cmd.exe and redirecting my_exec.exe output to both the console and an output.txt file:
powershell ".\my_exec.exe | tee output.txt"
An example (from cmd.exe) which holds open stdout/stderr and doesn't require tee or a temporary file:
my_exec.exe > NUL 2>&1
Easy
Step1: Create new project. Go File->New File or Project --> Other Project -->Empty Project
Step2: Use the below code.
In .pro file
QT +=widgets
CONFIG += console
TARGET = minimal
SOURCES += \ main.cpp
Step3: Create main.cpp and copy the below code.
#include <QApplication>
#include <QtCore>
using namespace std;
QTextStream in(stdin);
QTextStream out(stdout);
int main(int argc, char *argv[]){
QApplication app(argc,argv);
qDebug() << "Please enter some text over here: " << endl;
out.flush();
QString input;
input = in.readLine();
out << "The input is " << input << endl;
return app.exec();
}
I created necessary objects in the code for your understanding.
Just Run It
If you want your program to get multiple inputs with some conditions. Then past the below code in Main.cpp
#include <QApplication>
#include <QtCore>
using namespace std;
QTextStream in(stdin);
QTextStream out(stdout);
int main(int argc, char *argv[]){
QApplication app(argc,argv);
qDebug() << "Please enter some text over here: " << endl;
out.flush();
QString input;
do{
input = in.readLine();
if(input.size()==6){
out << "The input is " << input << endl;
}
else
{
qDebug("Not the exact input man");
}
}while(!input.size()==0);
qDebug(" WE ARE AT THE END");
// endif
return app.exec();
} // end main
Hope it educates you.
Good day,
First of all you can try flushing the buffer
std::cout << "Hello, world!"<<std::endl;
For more Qt based logging you can try using qDebug.