Custom QWidget in different file than main function - c++

I have a little question about Qt custom Widgets.
Both in http://doc.qt.digia.com/4.3/tutorial-t4.html and http://doc.qt.digia.com/4.3/tutorial-t8.html, the custom window declaration is made in the main.cpp file, where the qApp pointer is accesible(in the second link, more widgets are declared in their own files).
Couldn't the window be done in another different file and have the qApp pointer passed to it?.

Yes, the main windows can be created in another file. All you need in the main is to create the QApplication and show something that you include. And then start the event loop.
You don't have to pass qApp pointer anywhere. It is a global reference to the only single application that can be running. Just access it in any other file by including QApplication.
Also be advised, those tutorials are for Qt 4.3 which is old (unless you are bound to use that version right now). You can find tutorials for Qt 4.8 here

Related

need help in a Qt Creator C++ app using Open GL

I'm writing an app in Qt Creator, using C++. The eventual goal is to have control over an OpenGL window from within the Qt main winow.
Initialization is fine, both mainwindow and OpenGL window start up with no issues.
The mainwindow is subclassed from QMainwindow, the OpenGL window is subclassed from public QWindow, public QOpenGLFunctions.
Here's the crux of the problem. I want event handlers in mainwindow to have access to the OpenGLWindow. I can't seem to make that happen. I've gotten past a number of obstacles so at this point I have the following set-up;
In main.cpp, I declare the objects for both mainwindow and OpenGLWindow. I have the mainwindow mousepressed event handler in main.cpp. As is, all works fine. Both windows come up as they should, and the event handler code does exactly what I want it to do in the mainwindow, just print some text in a textbox.
In order to have access to the openglwindow from the event handler in main.cpp, I declare the OpenGLWindow object as global, outside of the main () main.cpp (is this bad technique?).
Everything compiles fine, but when I run it I get the error 'QPixmap: Must construct a QGuiApplication before a QPixmap'. I assume that this means that the system is not happy that I am creating the OpenGLWindow before the application object.
Is there a more elegant way to do this? Am I a few lines away from correct code, or does this need some major rearranging.
BTW - I am doing this in Windows 10. The main reason I have chosen Qt and OpenGL for this app is that I want it portable to Linux.

How are Qt signals/slots actually coupled to the elements in a .ui file?

I'm currently working on a Qt project and am somewhat confused with the signals and slots mechanism. I feel however that I have a somewhat good understanding between the differences between a QObject and user interface form.
A user interface form (described by a .ui file) is fed into the user interface compiler(uic) and produces an associated header file. This header file doesn't just contain interface information, but instead contains the implementation details on a QObject should be formatted. A QObject on the other hand is the base class in which a lot of the Qt framework is built upon. The signals and slot systems is based completely on the QObject.
When extending the QObject class (or from a derived class), you are actually defining an object in which can produce signals and slots. To format this object to look like the user interface you just designed in Qt Designer, you create an instance of the ui class (via the ui header generated by the uic). You call the setup method on this class and feed it the new QObject you're creating.
This all seems to make sense.
However, what doesn't make sense is when you start actually defining signals. From with Qt Designer, I have the option to right click and select a 'signal'. When I select a signal (whether that be a mouse click on a button or a change in a progress bar), it ends up adding that to my QObjects signals section. My question is: why and how? How exactly are my actions in Qt Designer (a program that generates an XML for the uic) getting coupled to my QObject in Qt Creator? More specifically, how does it know which QObject to add this slot to?
This question may be somewhat unclear, so I'll throw an example here.
Say for example I want to create a new interactive display of some kind. Let's call it 'MyScreen'. In order to create this interface, I would likely have 3 files: 'myscreen.h', 'myscreen.cpp', and 'myscreen.ui'. 'myscreen.h' is responsible for declaring the QObjects properties and methods as well as signals and slots. 'myscreen.cpp' is responsible for defining the methods, signals, and slots. 'myscreen.ui' is repsonible for creating the user interface layout that will be used to format an instance of MyScreen.
But due to what I had stated previously saying that the ui is just used for generating a header, why exactly is it coupled to 'myscreen.cpp'? That is, I can right click on the .ui layout, create a new signal type, and that signal type will be added to the myscreen.h and myscreen.cpp. How does this happen? How is it coupled? Does Qt operate such that there should always be 3 files (xxx.h, xxx.cpp, xxx.ui) that should exist?
So hopefully that gives you some context in what I'm confused about. There doesn't seem to be a well written document (that I've found at least), that thoroughly describes the underlying relationship between all these items.
TLDR - How does the signal/slot from the .h and .cpp actually link to the elements defined in the .ui file?
My question is: why and how? How exactly are my actions in Qt Designer (a program that generates an XML for the uic) getting coupled to my QObject in Qt Creator? More specifically, how does it know which QObject to add this slot to?
The short answer is: magic.
The real answer is, it actually has nothing to do with your actions in Designer, at least not directly. It's not actually even a UI-specific thing, it's just that designer makes good use of it. What happens is this:
First of all, any time you compile a file that makes use of the Q_OBJECT macro, this triggers Qt's moc tool to run during compilation ("triggers" isn't really the most accurate description: More precisely, when qmake is run to generate makefiles, it adds build rules to run moc when Q_OBJECT is detected in a header, but that's beside the point). Details are a bit outside the scope of this answer but long story short is it ultimately generates those moc_*.cpp files you'll see after compilation, which contain a whole bunch of compiled meta info. The important part of this is where it generates run-time accessible information about the various signals and slots you have declared. You'll see how that's important here below.
The other important thing is all QObjects have a name. This name is accessible at runtime. The name you give your widgets in designer is set as the widget's object name. The reason this is important will also become clear below.
And the final important thing is QObjects have a hierarchical structure; when you create a QObject you can set its parent. All of the widgets on your form ultimately have the form itself (e.g. your QMainWindow-derived class) as their parent.
Ok, so...
You'll notice in source code Qt generates for your windows you always have that ui->setupUi(this) call in the constructor. The implementation of that function is generated by Qt's uic tool during compilation, in e.g. ui_mainwindow.h. That function is where all the properties you set up in designer, stored in the .ui file, are actually set, including the widgets' object names. Now, the last line of the generated setupUI() implementation is the key:
void setupUi(QMainWindow *MainWindow) {
...
// Object properties, including names, are set here. This is
// generated from the .ui file. For example:
pushButton = new QPushButton(centralWidget);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
pushButton->setGeometry(QRect(110, 70, 75, 23));
...
// This is the important part for the signal/slot binding:
QMetaObject::connectSlotsByName(MainWindow);
}
That function, connectSlotsByName, is where the magic happens for all those widget signals.
Basically that function does the following:
Iterate through all your declared slot names, which it can do because this was all packed into runtime-accessible strings by moc in the meta object info.
When it finds a slot whose name matches the pattern on_<objectname>_<signalname>, it recursively searches the object hierarchy for an object whose name is <objectname>, e.g. one of your named widgets, or whatever other named objects you may have created. It then connects that objects signal, <signalname> to the slot it found (it basically automates calls to QObject::connect(...)).
And that's it.
So what this means is, nothing special actually happens in designer when you go to a slot there. All that happens is designer inserts a slot named on_widgetName_signalName, with the appropriate parameters, into your header and generates an empty function body for it. (thuga has added a great explanation of this). This is enough for QMetaObject::connectSlotsByName to find it at run time and set up the connection.
The implications here are very convenient:
You can remove a widget's signal handler without doing anything special in designer. You just remove the slot and its definition from your source file, it's all completely self contained.
You can add widget signal handlers by hand without having to go through the designer interface, which can save you some tedium sometimes. All you have to do is create a slot in your window named e.g. on_lineEdit1_returnPressed() and voila, it works. You just have to be careful, as hyde reminds us in a comment: If you make a mistake here you won't get a compile-time error, you will only get a run-time warning printed to stderr and the connection won't be created; so it's important to pay attention to console output if you make any changes here.
The other implication here is that this functionality isn't actually limited to UI components. moc runs for all your QObjects, and connectSlotsByName is always available. So any object hierarchy you create, if you name the objects, then declare slots with appropriate names, you can call connectSlotsByName to automatically set up connections; it just so happens that uic sticks that call at the end of setupUi, because that's a convenient place to put it. But the magic isn't UI-specific, and doesn't rely on uic, only on the meta info. It's a generally available mechanism. It's pretty neat.
As an aside: I stuck a quick example of QMetaObject::connectSlotsByName on GitHub.
What happens when you add a slot from the Go to slot... context menu item, is it goes through your project, and it looks for any files that include ui_myclass.h. When it finds this file, it then makes sure that Ui::MyClass object is declared either in that file, or in directly included files. These would be your myclass.cpp and myclass.h files. If it finds these files, it will then add the slot declaration and the definition in those files.
You can test this by removing the Ui::MyClass object (usually named ui) declaration from your myclass.h file, and then adding a slot by using the Go to slot... function in the designer. You should get some error message stating it couldn't find Ui::MyClass object declaration.
You can also try removing the ui_myclass.h inclusion from your myclass.cpp file. If you try adding a slot from the designer now, you will get an error message stating that it couldn't find ui_myclass.h included anywhere, or something like that.
If you define everything just inside your myclass.h file and remove myclass.cpp, it should give you an error message stating that it is unable to add the slot definition.
You can inspect how it works in more detail by looking at this part of the source code.
But in the end what really matters is, that you declare and define your class methods in separate .h and .cpp files, and that ui_xxx.h is included and that Ui::xxx object has been declared in those files. Of course this is what Qt Creator does for you automatically when you add a new form class, so you don't have to worry about it.

Dynamical overriding

I want to dynamically instantiate a QWidget and bind its "Pressed" event, either with a Qt signal or by overriding a function.
However I'm only allowed to create one new .cpp file.
I don't know how to override a C++ function dynamically, or how to change a virtual function into a Qt signal.
Is what is represented in the picture above achievable ?
The Widgets Tutorial of the Qt docs is a nice starting point.
Under Qt Widgets Examples you can find the Calculator Example, which should contain all of what you want to do.
Take the code, strip it down to what you need, use and try to understand it.
Or maybe have a look at the Getting Started section.

QT: How do I share same object in all .ui

I'm new to QT and this is probably (I hope) easy to solve, but i really dont know how to do it.
My program is quite easy, mainwindow with few buttons, but what my problem is:
In main.cpp I load a list from file and save it in a pointer (ex: listPointer) and I need to acces the info, from that list from many different .ui and .cpp (I mean, the Qt Class Form Pack, .ui .h .cpp).
I donĀ“t know which way is the best to do this. In mainwindow.h I added a list pointer to get the reference and in the .cpp acces it via this->listPointer and that works, but when i try to acces it from other Qt class (ex: Search.cpp) my app just crashes, obviusly becouse I'm trying to access wrong memory block.
So my problem is, how do I share this list to all the QT Objects.
I hope you understand my problem, english is not my native so maybe u dont.
If your main window exists throughout the life of your application and you only need a one instance of your main window, you can simply make your main window class singleton. You can keep your list pointer as a member of main window and add a getter method to it.
Then you can access your list from anywhere of your application like this
QList<String>* list = MyMainWindow::getInstance()->getList();

Showing a window over the curent one in qt from necessitas

I'm using Necessitas to compile and run my QT apps on Android. If I'd like to show another window over the Main Wondow, I would create an UI file from QT Creator, which also will create a class. Then, I would create an instance of that class, and finally call the exec() member function.
However, in Necessitas QT Creator, the compiler tells me that the memeber function exec() doesen't exist. If I try using the show() member function, nothing happens. Also , If I hide the Main Window, the program exits.
So ,what can I do to show the other Window that I created with QT Creator?
http://qt-project.org/doc/qt-4.8/qstackedwidget.html
This is essentially a layout that behaves like a tabbed/paged widget but it doesn't show any tabs. This should get you what you want.