0

complete beginner here. I'm trying to execute a function whenever pushButton is pressed, but it only gets executed after I close the main window. How can I make this happen instantly whenever the button is pressed?

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>

using namespace std;

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

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

void MainWindow::on_pushButton_clicked()
{
    cout << "test";
}

"test" is printed only after the window is closed. Same thing happens when I call my own function.

Q5123
  • 9
  • 1
  • Try turning off buffering for your `cout` statement. See http://stackoverflow.com/questions/1377084/unbuffered-output-with-cout. – RA. Feb 12 '15 at 21:07

2 Answers2

0

if you are just debugging/testing and you don't intend for your final application to use this, you could try the following:

#include <QDebug>

    void MainWindow::on_pushButton_clicked()
    {
        qDebug() << "test";
    }
luffy
  • 2,246
  • 3
  • 22
  • 28
0

try:

void MainWindow::on_pushButton_clicked()
{
    std::cout << "test" << std::endl;
}

By providing the endl; the set:cout buffer is flushed, you could also add std::cout << std::flush; to flush the buffer.

Also please avoid using namespace std;

Community
  • 1
  • 1
WiBu
  • 34
  • 6
  • You see in code that you added the namespace: `using namespace std;`, so it is not necessary to use `std ::` – eyllanesc May 09 '17 at 22:17
  • @eyllanesc True, however, in general it is better practice to remove using namespace std and prefix with `std::`. so to be consistent I should use `std::endl` as well, i edited my answer to make it consistent. [link] (http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – WiBu May 10 '17 at 12:34
  • That I know, it is a bad practice but that does not influence the OP. – eyllanesc May 10 '17 at 14:26
  • @eyllanesc Thanks for pointing out the inconsistency in my answer. I decided to edit it to make it conform best practice, rather than taking out the std:: – WiBu May 10 '17 at 14:56