Creating a window in Qt outside of main()?
Is it possible to make a window in Qt outside of the main() function like it's done in the tutorials? What's wrong with they way I did it here? There are no errors when I try to compile, but the window just never shows up. Thanks.
main.cpp
#include <QtGui>
#include "Calculator.h"
int main(int argc, char *argv[]) {
开发者_JAVA百科 QApplication application(argc, argv);
Calculator calculator();
return application.exec();
}
Calculator.h
class Calculator {
public:
Calculator();
};
Calculator.cpp
#include <QtGui>
#include "Calculator.h"
Calculator::Calculator() {
QWidget window;
window.show();
}
Curiously, you have two separate errors here :)
window
is a local variable in the constructor that goes out of scope (and thus is destroyed) once the constructor exits. You must use a persistent object (one that lives after the function exits), such as a member ofCalculator
.- In
main
, the codeCalculator calculator();
declares a functioncalculator
returningCalculator
. This is a common gotcha when instantiating default-constructed objects in C++. The parentheses are unnecessary (and harmful) in this case.
To fix both errors:
class Calculator {
public:
Calculator();
private:
QWidget m_window; // persistent member
};
Calculator::Calculator() {
m_window.show();
}
int main(int argc, char *argv[]) {
QApplication application(argc, argv);
Calculator calculator; // note, no () after calculator
return application.exec();
}
精彩评论