I am new to QT GUI programming.
I am trying to test switching two mainwindows continously by using show and hide.
I have created a simple code in main.cpp
main(){
QApplication a(argc , argv)
Mainwinodw1 *window1 = new Mainwindow1();
Mainwinodw1 *window2 = new Mainwindow2();
for (;;)
{
window1->show();
delay();
window1->hide();
window2->show();
delay();
window2->hide();
}
return a.exec();
}
The test can display the windows only one time , but duirng the second iteration they dont show and hide.
Can somebody help to fix this.
Try to use Qt timers instead of hardcoded delay function.
main.cpp file:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Mainwindow1 *window1 = new Mainwindow1();
Mainwindow2 *window2 = new Mainwindow2();
WindowSwitcher ws(window1, window2, 2000);
window1->show();
return a.exec();
}
WindowSwitcher source code:
#include "windowswitcher.h"
#include <QTimer>
WindowSwitcher::WindowSwitcher(QMainWindow *w1, QMainWindow *w2, int delay) : QObject(), window1(w1), window2(w2)
{
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(switchWindow()));
timer->start(delay);
}
void WindowSwitcher::switchWindow()
{
if (window1->isVisible())
{
window1->hide();
window2->show();
}
else
{
window1->show();
window2->hide();
}
}
WindowSwitcher header file:
#include <QObject>
#include <QMainWindow>
class WindowSwitcher : public QObject
{
Q_OBJECT
public:
explicit WindowSwitcher(QMainWindow *w1, QMainWindow *w2, int delay);
private:
QMainWindow *window1;
QMainWindow *window2;
public slots:
void switchWindow();
};
Related
I am using the Urho3D engine with Qt for an application. The problem is that both Urho3D and QApplication require to be ran from main(). For now I am using it in separate processes but IPC makes it complicated.
Is there any way to solve this issue? Thanks
My platform is Urho3D 1.5, Qt 4.71 and Windows 7 x64 and VS2015 (C++)
I'm new to both c++ and Urho3D, but I've successfully achieved it.
Simple code, haven't had further test:
awidget.h:
#ifndef AWIDGET_H
#define AWIDGET_H
#include <QWidget>
#include <QPushButton>
#include <Urho3D/Engine/Application.h>
class aWidget : public QWidget
{
Q_OBJECT
public:
explicit aWidget(QWidget *parent = 0)
{
QPushButton *button = new QPushButton(this);
connect(button, SIGNAL(clicked()), this, SLOT(pressed()));
}
public slots:
void pressed()
{
Urho3D::Context* context = new Urho3D::Context();
Urho3D::Application *application = new Urho3D::Application(context);
application->Run();
}
};
#endif // AWIDGET_H
main.cpp:
#include <QApplication>
#include <awidget.h>
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
aWidget *widget = new aWidget();
widget->show();
return app.exec();
}
By the way, I'm using Qt 5.9.0
So the answer is quite simple. Instead of running QApplication by calling
app->exec();
it is needed to manually and regularily call this from your main loop:
app->processEvents();
This will take care that all events used by Qt are processed and QApplication will respond accordingly.
Example:
#include <QApplication>
#include <awidget.h>
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
bool shallrun = true;
aWidget *widget = new aWidget();
widget->show();
while (shallrun)
{
app->processEvents();
...
}
...
}
My example:
main.cpp:
QApplication a(argc, argv);
MainWindow w;
w.start();
return a.exec();
w.start():
if (cf.exec()){
this->show();
} else {
qDebug()<<"Need exit";
//here should be exit
}
At comment place, I tried to do: qApp->exit() and qApp->quit() and this->close() (but 'this' not shown and of cource close() is not working). How can I finish app from any place of code?
Whole code:
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.start();
return a.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "CadrForm.h"
#include "TeacherForm.h"
#include "DepartmentForm.h"
#include "CategoriesForm.h"
#include "PostForm.h"
#include "RanksAndDegreesForm.h"
#include "TeachersRankAndDegreeForm.h"
#include "ConnectionForm.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
void start();
~MainWindow();
signals:
void widgetChanged(QWidget*);
private slots:
void on_actionCadr_triggered();
void resetMainLayout(QWidget* w);
void on_actionTeacher_triggered();
void on_actionDepartment_triggered();
void on_actionPost_triggered();
void on_actionCategories_triggered();
void on_actionRanksAndDegrees_triggered();
void on_actionTeachersRD_triggered();
private:
ConnectionForm cf;
CadrForm *cadrForm;
TeacherForm *teacherForm;
DepartmentForm *departmentForm;
CategoriesForm *categoriesForm;
PostForm *postForm;
RanksAndDegreesForm *ranksAndDegreesForm;
TeachersRankAndDegreeForm *teachersRankAndDegreeForm;
QWidget *current;
Ui::MainWindow *ui;
void addWidgetToMainLayout(QWidget *w);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
connect(this, SIGNAL(widgetChanged(QWidget*)), this, SLOT(resetMainLayout(QWidget*)));
ui->setupUi(this);
cadrForm = new CadrForm(this);
teacherForm = new TeacherForm(this);
departmentForm = new DepartmentForm(this);
categoriesForm = new CategoriesForm(this);
postForm = new PostForm(this);
ranksAndDegreesForm = new RanksAndDegreesForm(this);
teachersRankAndDegreeForm = new TeachersRankAndDegreeForm(this);
addWidgetToMainLayout(cadrForm);
addWidgetToMainLayout(teacherForm);
addWidgetToMainLayout(departmentForm);
addWidgetToMainLayout(categoriesForm);
addWidgetToMainLayout(postForm);
addWidgetToMainLayout(ranksAndDegreesForm);
addWidgetToMainLayout(teachersRankAndDegreeForm);
}
void MainWindow::start()
{
if (cf.exec()){
this->show();
} else {
qDebug()<<"Need exit";
qApp->quit();
qDebug()<<"still working";
}
}
void MainWindow::addWidgetToMainLayout(QWidget *w)
{
ui->mainLayout->insertWidget(0, w);
ui->mainLayout->itemAt(0)->widget()->hide();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::resetMainLayout(QWidget *w)
{
int index;
if (current)
{
index = ui->mainLayout->indexOf(current);
ui->mainLayout->itemAt(index)->widget()->hide();
}
index = ui->mainLayout->indexOf(w);
if (index != -1) ui->mainLayout->itemAt(index)->widget()->show();
else {
addWidgetToMainLayout(w);
resetMainLayout(w);
}
current = w;
setWindowTitle(current->windowTitle());
}
void MainWindow::on_actionCadr_triggered()
{
emit widgetChanged(cadrForm);
}
void MainWindow::on_actionTeacher_triggered()
{
emit widgetChanged(teacherForm);
}
void MainWindow::on_actionDepartment_triggered()
{
emit widgetChanged(departmentForm);
}
void MainWindow::on_actionPost_triggered()
{
emit widgetChanged(postForm);
}
void MainWindow::on_actionCategories_triggered()
{
emit widgetChanged(categoriesForm);
}
void MainWindow::on_actionRanksAndDegrees_triggered()
{
emit widgetChanged(ranksAndDegreesForm);
}
void MainWindow::on_actionTeachersRD_triggered()
{
emit widgetChanged(teachersRankAndDegreeForm);
}
And ConnectionForm - it's just a QDialog with some GUI and without any additional code.
It looks like the problem is you're not allowed to call QApplication::quit() or QApplication::exit() until the QApplication event loop has actually started. The event loop gets started by QApplication::exec(), so you're calling quit()/exit() too soon for it to have an effect.
You can fix this either by moving the quit()/exit() call so that it's in the event loop (e.g. by moving your MainWindow::start() code to the QMainWindow::showEvent() slot), or by changing your MainWindow::start() to return a value, inspect that value in main, and exit (without calling QApplication::exec()`) if it's a value that indicates your process should exit early.
Since you start the dialog event loop "early" - which is blocking -, you do not get to the event loop of the application.
If this is an intentional design, you better call exit(3) and remove the application event loop.
If you want to have the application event loop running, then you will need to make sure that it runs before you get to the point of your dialog execution.
The quick fix would be to start a single shot QTimer right just before the application event loop is started and that would trigger your "start" method call.
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.start();
QTimer::singleShot(200, w, SLOT(start()));
return a.exec();
}
and change the start to a slot, respectively.
In the long run, you may wish to consider a button and so on for bringing your dialog up, however.
The idiomatic way of queuing a method call until the event loop gets a chance to run is:
QMetaObject::invokeMethod(&w, "start", Qt::QueuedConnection);
Thus, your main would become:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
QMetaObject::invokeMethod(&w, "start", Qt::QueuedConnection);
return a.exec();
}
Hi my program runs with no errors but nothing is displayed on screen, a window is meant to pop up which runs another program with a QProcess, this program runs fine. code follows:
header file:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtGui>
#include <QTimer>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void setTimer();
void displayAdvice();
void cancelTimer();
void addAdvice();
void processDone(int);
private:
QLabel* timerLbl;
QLineEdit* timerEdt;
QTextEdit* adviceEdt;
QPushButton* okBtn;
QPushButton* cancelBtn;
QTimer* timer;
QProcess *process;
void setupGui();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setupGui();
}
Widget::~Widget()
{
delete ui;
}
void Widget::setupGui()
{
timerLbl = new QLabel("Timer set interval in seconds");
timerEdt = new QLineEdit();
adviceEdt = new QTextEdit();
this->adviceEdt->setReadOnly(true);
okBtn = new QPushButton("OK");
cancelBtn = new QPushButton("Cancel");
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(timerLbl);
layout->addWidget(timerEdt);
layout->addWidget(okBtn);
layout->addWidget(adviceEdt);
layout->addWidget(cancelBtn);
this->setWindowTitle("Advice");
this->setLayout(layout);
connect(okBtn,SIGNAL(clicked()), this, SLOT(setTimer()));
connect(cancelBtn, SIGNAL(clicked()), this, SLOT(cancelTimer()));
connect(timer, SIGNAL(timeout()),this, SLOT(displayAdvice()));
}
void Widget::setTimer()
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),this, SLOT(cancelTimer()));
QString setting = this->timerEdt->text();
bool ok;
int set = setting.toInt(&ok,10);
set = set * 1000;
timer->setInterval(set);
timer->start();
timerEdt->setReadOnly(true);
okBtn->setDown(true);
}
void Widget::cancelTimer()
{
timer->stop();
adviceEdt->clear();
okBtn->setDown(false);
timerEdt->clear();
timerEdt->setReadOnly(false);
}
void Widget::displayAdvice()
{
process = new QProcess(this);
process->start("C:/Users/Dmon/Desktop/47039949 COS3711 Assignment 2/Question 4/Ass2Q4Part1-build-desktop/debug/Ass2Q4Part1.exe");
connect(process, SIGNAL(readyReadStandardOutput()),this, SLOT(addAdvice()));
connect(process, SIGNAL(finished(int)),this, SLOT(processDone(int)));
}
void Widget::addAdvice()
{
QByteArray data = process->readAllStandardOutput();
QString strToWrite = data;
this->adviceEdt->clear();
this->adviceEdt->append(strToWrite);
}
void Widget::processDone(int)
{
process->close();
process->deleteLater();
process=0;
}
main.cpp
#include <QtGui/QApplication>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
Program runs with nothing displayed then eventually exits with no errors after about 15 seconds.
Your problem is that you're already using a user interface coming from the form file (.ui file). You need to decide which one you wish to use.
To fix your code, all you need to do is remove all references to the Ui namespace. Simply remove the below:
namespace Ui {
class Widget;
}
//
private:
Ui::Widget *ui;
//
#include "ui_widget.h"
//
delete ui;
Also, note that this line is working with a null or undefined pointer value - you never create the timer instance:
connect(timer, SIGNAL(timeout()),this, SLOT(displayAdvice()));
Finally, there's no reason whatsoever to allocate the member widgets on the heap. It does, in fact, waste a bit of heap memory since QWidget instances are very small.
Here's how your code could look. I've put it all in a single file, to keep it short. You obviously don't need it in a single file. I've also made the UI a bit more compliant with usual expectations. E.g. controls that can't be interacted with should be disabled.
// main.cpp
#include <QApplication>
#include <QtWidgets>
#include <QTimer>
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
private slots:
void setTimer();
void displayAdvice();
void cancelTimer();
void addAdvice();
void processDone(int);
private:
QLabel m_timerLbl;
QLineEdit m_timerEdt;
QTextEdit m_adviceEdt;
QPushButton m_okBtn;
QPushButton m_cancelBtn;
QTimer m_timer;
QProcess m_process;
void setupGui();
};
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
setupGui();
}
void Widget::setupGui()
{
m_timerLbl.setText("Timer set interval in seconds");
m_adviceEdt.setReadOnly(true);
m_okBtn.setText("OK");
m_cancelBtn.setText("Cancel");
m_cancelBtn.setEnabled(false);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(&m_timerLbl);
layout->addWidget(&m_timerEdt);
layout->addWidget(&m_okBtn);
layout->addWidget(&m_adviceEdt);
layout->addWidget(&m_cancelBtn);
setWindowTitle("Advice");
connect(&m_okBtn, SIGNAL(clicked()), SLOT(setTimer()));
connect(&m_cancelBtn, SIGNAL(clicked()), SLOT(cancelTimer()));
connect(&m_timer, SIGNAL(timeout()), SLOT(displayAdvice()));
connect(&m_timer, SIGNAL(timeout()), SLOT(cancelTimer()));
connect(&m_process, SIGNAL(readyReadStandardOutput()), SLOT(addAdvice()));
connect(&m_process, SIGNAL(finished(int)), SLOT(processDone(int)));
}
void Widget::setTimer()
{
QString const setting = m_timerEdt.text();
bool ok;
int set = setting.toInt(&ok,10) * 1000;
m_timer.setInterval(set);
m_timer.start();
m_timerEdt.setEnabled(false);
m_okBtn.setEnabled(false);
m_cancelBtn.setEnabled(true);
}
void Widget::cancelTimer()
{
m_timer.stop();
m_adviceEdt.clear();
m_timerEdt.clear();
m_okBtn.setEnabled(true);
m_timerEdt.setEnabled(true);
m_cancelBtn.setEnabled(false);
}
void Widget::displayAdvice()
{
m_process.start("bash", QStringList() << "-c" << "echo 'Hello!'");
#if 0
m_process.start(QDir::homePath() +
"/Desktop/47039949 COS3711 Assignment 2/Question 4/Ass2Q4Part1-build-desktop/debug/Ass2Q4Part1.exe");
#endif
}
void Widget::addAdvice()
{
QByteArray const data = m_process.readAllStandardOutput();
m_adviceEdt.setPlainText(QString::fromLocal8Bit(data));
}
void Widget::processDone(int)
{
m_process.close();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
#include "main.moc"
This question already has answers here:
C++ Qt signal and slot not firing
(3 answers)
Closed 8 years ago.
I am very new to Qt and it looks like i have some very basic misunderstanding about how this library works. I am currently reading a book by m. Schlee but i do not want to continue until i do understand how to make this simple program work.
#include <QtWidgets>
#include <QApplication>
#include <QStackedWidget>
#include <QPushButton>
#include <QObject>
struct wizard : public QObject
{
QStackedWidget* p;
wizard(QStackedWidget* pp) : p(pp) { }
public slots:
void change()
{
int to = p->currentIndex();
if (to == p->count() - 1)
to = 0;
else
++to;
emit chIndex(to);
}
signals:
void chIndex(int);
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStackedWidget qsw;
QPushButton qpb("magic");
qsw.resize(500, 500);
qsw.move(500, 300);
qsw.setWindowTitle("test qsw");
qpb.move(330, 300);
qpb.setWindowTitle("test qpb");
QWidget* pw1 = new QWidget();
QPalette pal1;
pal1.setColor(pw1->backgroundRole(), Qt::blue);
pw1->setPalette(pal1);
pw1->resize(500, 500);
pw1->setAutoFillBackground(true);
QWidget* pw2 = new QWidget();
QPalette pal2;
pal2.setColor(pw2->backgroundRole(), Qt::yellow);
pw2->setPalette(pal2);
pw2->resize(500, 500);
pw2->setAutoFillBackground(true);
qsw.addWidget(pw1);
qsw.addWidget(pw2);
wizard stupidity(&qsw);
QObject::connect(&qpb, SIGNAL(clicked()), &stupidity, SLOT(change()));
QObject::connect(&stupidity, SIGNAL(chIndex(int)), &qsw, SLOT(setCurrentIndex(int)));
qpb.show();
qsw.show();
return a.exec();
}
The idea is to launch 2 separate windows: one with painted background, and another with button that changes color (blue->yellow->blue->.. etc).
They appear, but nothing happens if i press the button. Please help.
Except for struct being a class and a missing Q_OBJECT macro the code is fine
Try the following:
create a main.h file having this content:
#ifndef MAIN_H
#define MAIN_H
#include <QObject>
#include <QStackedWidget>
class wizard : public QObject
{
Q_OBJECT
public:
QStackedWidget* p;
wizard(QStackedWidget* pp) : p(pp) { }
public slots:
void change()
{
int to = p->currentIndex();
if (to == p->count() - 1)
to = 0;
else
++to;
emit chIndex(to);
}
signals:
void chIndex(int);
};
#endif // MAIN_H
change your main.cpp to the following content:
#include <QtWidgets>
#include <QApplication>
#include <QPushButton>
#include <main.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStackedWidget qsw;
QPushButton qpb("magic");
qsw.resize(500, 500);
qsw.move(500, 300);
qsw.setWindowTitle("test qsw");
qpb.move(330, 300);
qpb.setWindowTitle("test qpb");
QWidget* pw1 = new QWidget();
QPalette pal1;
pal1.setColor(pw1->backgroundRole(), Qt::blue);
pw1->setPalette(pal1);
pw1->resize(500, 500);
pw1->setAutoFillBackground(true);
QWidget* pw2 = new QWidget();
QPalette pal2;
pal2.setColor(pw2->backgroundRole(), Qt::yellow);
pw2->setPalette(pal2);
pw2->resize(500, 500);
pw2->setAutoFillBackground(true);
qsw.addWidget(pw1);
qsw.addWidget(pw2);
wizard stupidity(&qsw);
QObject::connect(&qpb, SIGNAL(clicked()), &stupidity, SLOT(change()));
QObject::connect(&stupidity, SIGNAL(chIndex(int)), &qsw, SLOT(setCurrentIndex(int)));
qpb.show();
qsw.show();
return a.exec();
}
qmake doesn't work very well with Q_OBJECT macro directly in cpp file. Btw. run qmake after changes applied.
Since Qt is using Cocoa under OSX, is it possible to make a modal QDialog to shake if the user enters the wrong password for example? Im not able to find anything about it but it would be really nice to implement on mac.
Thanks!
I'm not aware of a built-in way to do it, but you could implement the shaking yourself, like this:
header.h
#include <QtGui>
class ShakyDialog : public QDialog
{
Q_OBJECT
public slots:
void shake()
{
static int numTimesCalled = 0;
numTimesCalled++;
if (numTimesCalled == 9) {
numTimesCalled = 0;
return;
}
vacillate();
QTimer::singleShot(40, this, SLOT(shake()));
}
private:
void vacillate()
{
QPoint offset(10, 0);
move(((shakeSwitch) ? pos() + offset : pos() - offset));
shakeSwitch = !shakeSwitch;
}
bool shakeSwitch;
};
main.cpp
#include "header.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
ShakyDialog dialog;
QHBoxLayout layout(&dialog);
QPushButton button("Push me.");
layout.addWidget(&button);
QObject::connect(&button, SIGNAL(clicked()), &dialog, SLOT(shake()));
dialog.show();
return app.exec();
}