I have a Qdialog in which i get some inputs to use on my mainwindow. so it must appear first than mainwindow.
the problem is that my mainwindow does not show up. here's my main.cpp
#include <QtGui/QApplication>
#include "planevolume.h"
#include "dialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Dialog *dialog= new Dialog;
dialog->show();
planevolume mainwindow;
bool dialogcheck = dialog->isHidden();
if (dialogcheck==1)
{
mainwindow.show();
}
else
{
}
return app.exec();
}
I have a pushbutton that when pressed hides the qdialog and if it is hidden than the mainwindow should show up, right?
here's the SLOT i used:
void Dialog::startplanevolume()
{
if (xMax==0 || yMax==0 || zMax==0 || xMMax==0 || yMMax==0 || zMMax==0)
{
ui->label_17->setText("Error: Can't start, invalid measures");
}
else
{
hide();
}
}
the mainwindow can only start after that button is clicked as only then I have the inputs to the main winodw
So the problem here is that calling dialog->show() does not block execution. The minute that call is made, it moves on to the next method. You need to block execution until the user finishes putting input in.
Make your main like this:
QApplication app(argc, argv);
Dialog *dialog= new Dialog;
if ( dialog->exec() ) {
planevolume mainwindow;
mainwindow.show();
return app.exec();
}
return 0;
And in your dialog class, make your method look like:
void Dialog::startplanevolume()
{
if (xMax==0 || yMax==0 || zMax==0 || xMMax==0 || yMMax==0 || zMMax==0)
{
ui->label_17->setText("Error: Can't start, invalid measures");
}
else
{
this->accept(); // close the dialog with a result of 1
}
}
When you press the button, you call your Dialog::startplanevolume, yes, but that's it. You don't go back to the main loop.
If you want to display your mainwindow, you may want to call a planevolume.show() in your Dialog::startplanevolume, just after the hide.
It might be tricky if your objects are in different files, though. So maybe you could define a signal like DialogChecked, emit this signal in your Dialog::startplanevolume (after the hide, of course...), and modify your main so that it would call mainwindow.setVisible(1) when receiving a DialogChecked.
The PushButton action may happen only after app.exec() is called. It makes no sense testing dialog properties before the main loop is entered.
The expected behavior may be reached by setting up the components to start sequentially in an asynchronous way. In Qt world, this means using signals and slots.
connect(dialog, SIGNAL(accept()), &mainwindow, SLOT(show()));
Related
I'm new to QT and I'm having issues when calling QFileDialog from a child window. My app is relatively simple. I have one prompt widget that gets user input and then runs show on its parent.
This is my main.
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
ParentWidjet w(nullptr);
ChildWidget input(&w);
input.show();
return a.exec();
}
This is the relevant section of the child widget:
ChildWidget::ChildWidget(QWidget *parent) :
QDialog(parent),
ui(new Ui::InputPrompt){
ui->setupUi(this);
this->setParent(parent);
}
...
void ChildWidget::on_imagesSelect_clicked() {
inputFilepath = QFileDialog::getExistingDirectory(static_cast<ParentWidget *>(this->parent()), QCoreApplication::translate("main", "Open directory"), "./", QFileDialog::ShowDirsOnly);
ui->inputPath->setPlainText(inputFilepath);
std::cout << "y u exit" << std::endl;
}
//Setup and show the parent
void ChildWidget::on_buttonBox_accepted() {
static_cast<ParentWidjet *>(this->parent())->setup(inputFilepath, outputFilepath);
static_cast<ParentWidjet *>(this->parent())->show();
}
For some reason when QFileDialog is called, closing it with either OK or Cancel closes both the parent and the child. If I don't use it, but click the OK button of the child, which calls the on_buttonBox_accepted() function, the child closes and the parent widget appears as expected. If I don't pass the parent widget to the child widget in the main, QFileDialog no longer closes the child widget when running. I tried changing the parent of QFileDialog to this or to nullptr but that didn't help.
I think my question is similar to QFileDialog closes window when called
or PyQt5 QFileDialog finishes app when called from child window
But i couldn't extract a solution from them that works for me.
Long story short, the second window is not shown, and there is no action waiting to receive the accept call, so my app just dies. This can be prevented if the quit on last window closed property is disabled. Qt forums suggested a solution, together with a few better design choices. This is what I went with in the end.
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
ParentWidget w(nullptr);
ChildWidget input;
if ( input.exec() == QDialog::accepted) // exec() blocks execution until ok/cancel. unlike show()
{
w.setup(input.inputFilepath, input.outputFilepath); // assuming these are public
w.show()
} else
{ // user closed or pressed cancelled
... what u want to do..
}
return a.exec();
}
I am developing a Qt application with multiple windows and want to implement cross-window drag&drop functionality for some elements in my program.
To do so, I attach an event filter to the to-be-dragged QML elements and listen for the MousePress/MouseMove events to start the drag procedure as follows:
QDrag *drag = new QDrag(quickItem);
QMimeData* mimeData = new QMimeData();
mimeData->setText("Test");
drag->setHotSpot(QPoint(0, 0));
drag->setMimeData(mimeData);
drag->exec();
This works fine, but now I would like to show a little tooltip (being a QWidget) while dragging, following the mouse cursor and displaying a short text depending on the element the mouse is currently over (similar to the "Copy to ..." or "Move to..." labels appearing when you drag files around in Windows Explorer).
However, while dragging the element, I don't receive any MouseMove events neither on the QDrag object nor on the quickItem itself, which makes it impossible to track the mouse position. Since the mouse is grabbed during dragging, there should be some event in Qt that frequently reports the mouse position, no matter where on the screen the mouse is.
I am aware of the QDrag::setPixmap method, however this won't allow me to change my tooltip text during dragging and has some other limitations I would like to avoid.
Is there some way to listen to mouse move events while QDrag is running, without using platform-specific system APIs?
Update:
I don't think that there is way of doing this without using OS libraries nor getting the mouse position every X miliseconds. It looks like a really specific problem that Qt framework does not contemplate. You will need to write your own class to control this using win32 for windows, x11 for linux and the equivalent of Mac.
If you want to get the mouse position when your window is active and you are dragging something, check this:
Searching a bit I've found a solution for getting it when your window has the focus using QObject::eventFilter.
Create a class (for example EventListener) that inherits from QObject and overrides eventFilter and a method to set this as your qml window (which inherits from QObject) event filter with installEventFilter.
eventslistener.h:
#include <QEvent>
#include <QObject>
#include <QDebug>
#include <QDropEvent>
class EventsListener : public QObject
{
Q_OBJECT
public:
EventsListener(QObject * ptr) : QObject (ptr) {
}
Q_INVOKABLE void handleEventsOf(QObject *object) {
if (object)
object->installEventFilter(this);
}
bool eventFilter(QObject *object, QEvent *event) override {
if(event->type() == QEvent::DragMove) {
QDragMoveEvent *mouseEvent = static_cast<QDragMoveEvent*>(event);
qDebug() << "Mouse position dragging (x, y): (" << mouseEvent->pos().x() << ", " << mouseEvent->pos().y() << ")";
return false; //this is must return false or drop event will be handled by this method and drag&drop won't work correctly
}
return false;
}
};
Now we need to access to an instance (singleton in this case) of this class with qmlRegisterSingletonType. You may wish to use qmlRegisterType instead to register this eventlistener as a type (instead of a singleton) and use signals to notify directly qml the mouse position.
main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "eventlistener.h"
static QObject *eventsListenerInstance(QQmlEngine *qmlEngine, QJSEngine *engine)
{
return new EventsListener(engine);
}
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterSingletonType<EventsListener>("AppEventListener", 1, 0, "EventsListener", eventsListenerInstance);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml:
import ...
import AppEventListener 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
id: item
property string display
property alias dropEnabled: acceptDropCB.checked
color: dropArea.containsDrag ? "#CFC" : "#EEE"
Component.onCompleted: EventsListener.handleEventsOf(item)
...
}
i'm using QT for the first time and got some problems with refreshing the GUI while adding elements.
The Code looks like:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
PObj obj;
MainWindow mw;
qRegisterMetaType<std::string>();
QObject::connect(&obj, SIGNAL(setText(std::string const&)),
&mw, SLOT(appendText(std::string const&)));
QFuture<void> f1 = QtConcurrent::run(&obj, &PObj::process);
mw.show();
f1.waitForFinished();
return a.exec();
}
With the PObj::process definition:
void PObj::process()
{
for(; ;)
{
sleep(1);
//do work and set text
std::string text = "bla";
emit setText( text );
}
}
And the MainWindow::appendText slot:
void MainWindow::appendText(std::string const& str )
{
ui->listWidget->addItem(QString::fromStdString(str));
}
I've tried placing qApp->processEvents() ,QCoreApplication::processEvents(); ... running wit future in the ThreadPool.
I thought running them with Concurrent::run is enough ?
UPDATE:
The question is, why the GUI isnt refreshed every second a new item is added ?
The f1.waitForFinished(); calls blocks until f1 is finished, as the name implies. This will never happen because you have the infinite loop. So your code will never get to main loop. You can't block the main thread like that! In general, avoid any WaitForXxxx() methods, especially the GUI thread.
Also, you have no way of stopping the process(); anyway, so waiting for it to finish doesn't make any sense... You might want to add a way to tell it to stop (such as atomic variable) but anyway, to fix your problem, simply remove the f1.waitForFinished(); line.
To terminate the task nicely, try adding QAtomicInt flag (not volatile boolean, it won't do), and then change the code like this:
Add member variable to PObj (should make it private and add setter):
QAtomicInt termianteFlag;
Change main like this:
int main(int argc, char *argv[])
{
///snip
QFuture<void> f1 = QtConcurrent::run(&obj, &PObj::process);
mw.show();
int ret = a.exec();
f1.terminateFlag = 1; // change this to setter method
f1.waitForFinished(); // this is not ideal, will wait for up to a second before exit
}
and
void PObj::process()
{
while(!terminateFlag)
{
sleep(1);
//do work and set text
std::string text = "bla";
emit setText( text );
}
}
I have a QML app in which I have subclassed QApplication to create my main screen with QML. The issue i have is on clicking Close button the application closes as intended, but I want to handle a situation where if some services are running I want to override close button behaviour.
I tried overriding closeEvent() without any luck. Can anyone point me to some ways I can handle this?
UPDATE : This is the code snippet I tried
class SingleApplication : public QApplication {
Q_OBJECT
public:
SingleApplication(int &argc, char **argv);
void closeEvent ( QCloseEvent * event )
{
event->ignore();
}
}
MAIN.cpp
#include "view.h"
#include <QDebug>
#include <QDesktopWidget>
#include "SingleApplication.h"
int main(int argc, char *argv[])
{
SingleApplication app(argc, argv);
if(!app.isRunning()) {
app.processEvents();
View view(QUrl("qrc:/qml/main.qml"));
#ifdef Q_OS_LINUX
view.setFlags(Qt::WindowMinimizeButtonHint|Qt::WindowCloseButtonHint);
#endif
view.setMaximumSize(QSize(1280,700));
view.setMinimumSize(QSize(1280,700));
// Centering the App to the middle of the screen
int width = view.frameGeometry().width();
int height = view.frameGeometry().height();
QDesktopWidget wid;
int screenWidth = wid.screen()->width();
int screenHeight = wid.screen()->height();
view.setGeometry((screenWidth/2)-(width/2),(screenHeight/2)-(height/2),width,height);
view.show();
return app.exec();
}
return 0;
}
There is no QApplication::closeEvent. Such virtual function belongs to QWidget.
Use of QApplication indicated that you have normal QWidget container for your QML UI (as you say UI is based on QML though). You should rather override that widget closeEvent e.g.:
class MyMainWidget : public QWidget // or is it QMainWindow?
{
// snip
private:
void closeEvent(QCloseEvent*);
}
void MyMainWidget::closeEvent(QCloseEvent* event)
{
// decide whether or not the event accepted
if (condition())
event->accept();
}
And if your container widget is not overridden yet (simply QWidget?), well, now you have to do so.
And you did not say whether or not you want to keep app window running. I assume you want that as well.
/EDIT: solved, see my comment in the 1st answer!/
I am currently building an application which only has a tray icon displayed, so it doesn't have any windows.
Well, in the tray icon I've included a QAction so as to close the application. The thing is, that I get seg fault when I call exit(0); from that function. This is some example code:
//I have a reason for setting it to be a QTimer, please don't even comment on this
class Boot_Timer : public QTimer {
Q_OBJECT
public:
explicit Boot_Timer(QObject *parent = 0) : QTimer(parent) {
}
public Q_SLOTS:
void set_up_command_line_tray(){
//Setting up the tray Icon.
QSystemTrayIcon *trayIcon_cmd = new QSystemTrayIcon(this);
trayIcon_cmd->setIcon(QIcon(":/icons/Pictures/myapp.png"));
trayIcon_cmd->setToolTip("My tray tooltipp");
QMenu *changer_menu = new QMenu;
QAction *Quit_action = new QAction(tr("&Quit"), this);
Quit_action->setIconVisibleInMenu(true);;
connect(Quit_action, SIGNAL(triggered()), this, SLOT(close_application()));
changer_menu->addAction(Quit_action);
trayIcon_cmd->setContextMenu(changer_menu);
trayIcon_cmd->show();
}
void close_application(){
//HERE I GET SEG FAULT
exit(0);
}
};
Boot_Timer boottimer;
#include "main.moc"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//making some checks (code omitted)
...
boottimer.set_up_command_line_tray()
return app.exec();
}
So, the tray icon is shown normally and perfectly, but when I choose to Quit the application using the menu I've added to the tray icon, I get a seg fault. I guess that I cannot quit the application using exit(int state) outside main() function and its functions that don't have a parent...
What is the correct way to quit my application, then?
Thanks in advance for any answers!
Try to call
qApp->quit(0);
instead of
exit(0);
Remember to #include <QApplication>.
Thanks, that didn't solve it. For some reason, the thing that solved it was to do the following: QSystemTrayIcon *trayIcon_cmd = new QSystemTrayIcon(0); instead of QSystemTrayIcon *trayIcon_cmd = new QSystemTrayIcon(this)