OpengGL glDrawBuffers() in Qt? - qt

is the OpenGL function glDrawBuffers(GLsizei n, const GLenum *bufs) available in Qt?
I'm trying to pass multiple render targets to my fragment shader, QtCreator says the function is not declared in this scope. The idea is to have a frame buffer object with two colorbuffers, and draw with the fragment shader to those two buffers.
FIXED:
Just had to add #define GL_GLEXT_PROTOTYPES 1 to the offending file :(

Qt offers only rudimentary access to OpenGL functions. Loading shaders and textures are amongst them. Render targets are not. Just use a proper extension loader library like GLEW. GLEW will nicely coexist with Qt's functionality.
Derive from QGLWidget and override glInit to call glewInit after calling initializeGL

We just spent some time fixing this. We are running Qt 5.2.1 on OSX 10.8 and Ubuntu 14.04 (sorry no WINDOWS experience) and created an OpenGL3.2 context using QGLFormat.
In OSX there is no problem as all OpenGL3.2 functions (to set uniforms, draw buffers, etc..) are defined in:
#include "OpenGL/gl3.h" ///< already included by Qt.. so nothing to do
On Linux on the other hand, we have to include BOTH of these:
#include "GL/gl.h"
#include "GL/glext.h" ///< not included by Qt!!! manually include it
We also attempted to have our QGLWidget class inherit from QGLFunctions_3_2_Core (this class defines its own copy of glDrawBuffer etc...), but this wasn't useful and simply resulted in a segfault:
Program received signal SIGSEGV, Segmentation fault. 0x0000000000407068
in glGetUniformLocation (this=0xbc5820, name=0x407cd0 "view_projection", program=1)
at /usr/include/qt5/QtGui/qopenglfunctions_3_2_core.h:1075 1075
return d_2_0_Core->GetUniformLocation(program, name);
We also investigated the "#define GL_GLEXT_PROTOTYPES 1" above, but this was only useful when we were using glcorearb.h (you can download this header online).

Related

Preprocessor makes function name unaccessabel

I have to create a SQLite database using System.Data.SQLite and using C++/CLI but I run into problems. Unfortunately, using C# is not an option, if it was then there is no problem. (Please don't advise me not to use C++/CLI, it is not an option in this project.)
In C# the following code works without any problem.
using System.Data.SQLite;
void CreateDb(String file)
{
SQLiteConnection.CreateFile(file);
}
The equivalent code in C++/CLI is not without its problems.
using namespace System::Data::SQLite;
void CreateDb(System::String ^file)
{
SQLiteConnection::CreateFile(file); // error C2039
}
The exact error txt for C2039 is:
// error C2039: 'CreateFileA' : is not a member of 'System::Data::SQLite::SQLiteConnection'
If I take a closer look at the definition of CreateFile I get the following choice
#define CreateFile CreateFileW - c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include\WinBase.h(9292)
#define CreateFile CreateFileA - c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include\WinBase.h(9294)
Which leads to the following lines in WinBase.h
#ifdef UNICODE
#define CreateFile CreateFileW
#else
#define CreateFile CreateFileA
#endif // !UNICODE
The Microsoft SDK is muddling with exact the name that I need and SQLite does not provide me with CreateFile[AW] versions.
So I tried this before the code calling SQLiteConnection.CreateFile(file) and I do this isolated so that other code is affected by it.
#ifdef CreateFile
#undef CreateFile
#endif
It solves my problem (for now) but how safe is this?
Is there a better way of solving this problem?
Your advise is much appreciated.
The #undef is how I've always handled this.
how safe is this?
This is safe.
You may have this problem again if you have other name collisions. The compile errors resulting from such a name collision are easy to diagnose, now that you know what you're looking for, so it will be easy to add additional #undef directives if needed.
If you need to call the Win32 CreateFile, you will need to type CreateFileA or CreateFileW explicitly, but that's not a big hassle.
Is there a better way of solving this problem?
Yes, but it's not always possible.
The better way is to not #include <Windows.h> in the files where you use SQLite. This avoids the problem entirely. However, it's not always possible to organize your program like this, so #undef is usually the solution.
(This next paragraph doesn't apply to your scenario with SQLite: You're using the managed version, so there's no headers. This next bit applies to C++ libraries that include library headers. I'm including it for completeness in case someone is writing plain C++.)
One other thing to watch out for here is #include-ing the Windows headers before library headers. In that case, the class definition itself will have CreateFile renamed to CreateFileA. If you use #undef with that, you'll get the opposite error from what you showed. You can leave the #define in place, which will sometimes end up working, but this is rather fragile, so I would avoid this scenario.
(I ran into this once with MFC headers in a C++ application: The changed method name ended up everywhere, even Intellisense showed the name as ending in "A". It worked anyway because the vTable was initialized inside the MFC DLL, and so all that mattered in the calling application was that the vTable pointed at the right method, which it was.)

SIGNAL & SLOT macros in Qt : what do they do?

I'm a beginner in Qt and trying to understand the SIGNAL and SLOT macros. When I'm learning to use the connect method to bind the signal and slot, I found the tutorials on Qt's official reference page uses:
connect(obj1, SIGNAL(signal(int)), obj2, SLOT(slot()))
However, this also works very well:
connect(obj1, &Obj1::signal, obj2, &Obj2::slot)
So what exactly do the macros SIGNAL and SLOT do? Do they just look for the signal in the class the object belongs to and return the address of it?
Then why do most programmers use these macros instead of using &Obj1::signal since the latter appears to be simpler and you don't need to change the code if the parameters of the signal function change?
The use of the SIGNAL and SLOT macros used to be the only way to make connections, before Qt 5. The connection is made at runtime and require signal and slots to be marked in the header. For example:
Class MyClass : public QObject
{
Q_OBJECT
signals:
void Signal();
slots:
void ASlotFunction();
};
To avoid repetition, the way in which it works is described in the QT 4 documentation.
The signal and slot mechanism is part of the C++ extensions that are provided by Qt and make use of the Meta Object Compiler (moc).
This explains why signals and slots use the moc.
The second connect method is much improved as the functions specified can be checked at the time of compilation, not runtime. In addition, by using the address of a function, you can refer to any class function, not just those in the section marked slots:
The documentation was updated for Qt 5.
In addition, there's a good blog post about the Qt 4 connect workings here and Qt 5 here.
Addition to the first answer.
what exactly did the macro SIGNAL and SLOT do
Almost nothing. Look at the qobjectdefs.h:
# define SLOT(a) "1"#a
# define SIGNAL(a) "2"#a
It just adds 1 or 2. It means that next code is valid and works as expected:
QObject *obj = new QObject;
connect(obj,"2objectNameChanged(QString)",this,"1show()");//suppose this is a pointer to a QDialog subclass
obj->setObjectName("newNAme");
why do most programmers use these macros instead of using like
&Obj1::signal
Because these macros work not only in Qt5.
Because with these macros there is no complexity with overloaded
signals (it can make your code very dirty and it is really not a simple thing)
Because with new syntax you sometimes need to use specific
disconnects
More details here.
To complete TheDarkKnight's answer, it is an excellent practice to refactor legacy code that is using the old Qt 4 SIGNAL and SLOT macros to Qt 5's new syntax using function address.
Suddenly, connection error will appear at compile time instead of at runtime! It's very easy to make a Qt 4 connection error as any spelling mistake will result in such an error. Plus, the name of the function must be the fully qualified name, i.e preceded with the full namespace if any.
Another benefit is the ability to use a lambda for the slot function, which can reduce need of a named function if the slot body is trivial.
These macros just convert their parameters to signal/slot-specific strings. The Differences between String-Based and Functor-Based Connections can be found in the docs. In short:
String-based:
Type checking is done at Run-time
Can connect signals to slots which have more arguments than the signal (using default parameters)
Can connect C++ functions to QML functions
Functor-based:
Type checking is done at Compile-time
Can perform implicit type conversions
Can connect signals to lambda expressions

How to set QCamera on label

I've decided no to use OpenCV. I will use the QCamera class. Everything is working perfect to this moment. I can capture and save images wherever I want, but the problem is how I can set the camera to a label or graphics view?
I mean, to see what is happening at the moment. When I make infinite loop everything crashes. Write any information you know, cause there are no examples how to do that, or I just can't see. If you can please write some source code.
Use QCameraVievFinder or QVideoWidget widgets ( docs - here) for that purpose, here is example for you:
#include <QCameraViewfinder>
// .......
QCamera *camera=new QCamera(this);
QCameraViewfinder *viewfinder = new QCameraViewfinder(this);
viewfinder->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);
camera->setViewfinder(viewfinder);
setCentralWidget(viewfinder);
//viewfinder->show();
camera->start(); // to start the viewfinder
Note: you need to add to your *,pro file this config to use them: QT += multimedia multimediawidgets
If you want a bit more low level widget (to process every frame the way you like (face detection etc), subclass QAbstractVideoSurface, docs - here
or try to connect to QVideoProbe class (docs - here), though i could not do it myself, this class is a bit experimental i guess, didn't worked

QVariantMap crash in destructor

I am building a JSON-object with Qt and convert it to a QString using QJson. This (normally) works fine and it does in this case but in the destructor of my Qt data structure, it crashes with an Access Violation. The Object is built fine, it is sent over my network connection and after the function ends, my application crashes.
My code looks like this:
void bar()
{
QVariantMap data;
data.insert("Id", 1);
QList<QVariant> list; //QVariantList
for (QMap<...>:ConstIterator ... ) //Loop through a Map
{
QMap<QString, QVariant> singleEntry; //QVariantMap
singleEntry.insert("LocalId", it.value());
QList<QVariant> entryList; //QVariantList
for (...) //Loop through another structure
{
entryList.append("foo");
}
singleEntry.insert("List", entryList);
list.append(singleEntry);
}
data.insert("Entries", list);
QJson::Serializer.serialize(data); // Works fine
} // Crash here
If I remove the inner loop, which builds up entryList, everything works fine. It seems that the destructor of data cannot delete the contents but I have no idea, why. The whole data structure seems to be fine while serializing it (and I hope that QJson does not change anything in the given data) but it cannot be cleaned up..
Best Regards,
Tobias
As Raiv said this can happen when mixing debug and release dlls, but in my oppinion this can also happen if the application and the Qt DLL's use different CRT libraries. Some people say that when they recompiled Qt on their machines the problem dissapears and I think this is because the CRT dlls after Qt rebuild are the same as the app's. Try to set the Runtime Library option in C/C++ Code Generation is set to Multi-threaded Debug DLL (/MDd) or Multi-threaded DLL (/MD) respectively for Debug and Release. Some Qt types as QVariantMap, QVariantList, QModelIndexList are probably allocated with /MD (in Qt's dll) and when they are deallocated with /MT (in the app) I think this causes the crash. This can also fix the crash on QString::toStdWString(). In order for this to link maybe the Ignore All Default Libraries should be set to No and Ignore Specific Library should not mention crt dlls used by Qt.
I got a little workaround, which fits my needs. I have still no idea, why this crash happens, but I know, which should be the problem.
I tried to build up a static structure like this:
QVariantMap
QVariantList
QVariantMap
QVariantList
and it crashes. If I remove the QVariantList at the bottom and add QVariantMap or anything else instead, it is working fine. I think this is a problem with the nesting level in this case.
I have now just joined my list as a comma-seperated QString and then it works fine.
If anyone of you has an idea, why the crash in destructing such a nested struct (another information: doesnt matter if a allocate the QVariants in heap and delete them myself or stack) and how to fix it, please let me know.

ld linker question: the --whole-archive option

The only real use of the --whole-archive linker option that I have seen is in creating shared libraries from static ones. Recently I came across Makefile(s) which always use this option when linking with in house static libraries. This of course causes the executables to unnecessarily pull in unreferenced object code. My reaction to this was that this is plain wrong, am I missing something here ?
The second question I have has to do with something I read regarding the whole-archive option but couldn't quite parse. Something to the effect that --whole-archive option should be used while linking with a static library if the executable also links with a shared library which in turn has (in part) the same object code as the static library. That is the shared library and the static library have overlap in terms of object code. Using this option would force all symbols(regardless of use) to be resolved in the executable. This is supposed to avoid object code duplication. This is confusing, if a symbol is refereed in the program it must be resolved uniquely at link time, what is this business about duplication ? (Forgive me if this paragraph is not quite the epitome of clarity)
Thanks
There are legitimate uses of --whole-archive when linking executable with static libraries. One example is building C++ code, where global instances "register" themselves in their constructors (warning: untested code):
handlers.h
typedef void (*handler)(const char *data);
void register_handler(const char *protocol, handler h);
handler get_handler(const char *protocol);
handlers.cc (part of libhandlers.a)
typedef map<const char*, handler> HandlerMap;
HandlerMap m;
void register_handler(const char *protocol, handler h) {
m[protocol] = h;
}
handler get_handler(const char *protocol) {
HandlerMap::iterator it = m.find(protocol);
if (it == m.end()) return nullptr;
return it->second;
}
http.cc (part of libhttp.a)
#include <handlers.h>
class HttpHandler {
HttpHandler() { register_handler("http", &handle_http); }
static void handle_http(const char *) { /* whatever */ }
};
HttpHandler h; // registers itself with main!
main.cc
#include <handlers.h>
int main(int argc, char *argv[])
{
for (int i = 1; i < argc-1; i+= 2) {
handler h = get_handler(argv[i]);
if (h != nullptr) h(argv[i+1]);
}
}
Note that there are no symbols in http.cc that main.cc needs. If you link this as
g++ main.cc -lhttp -lhandlers
you will not get an http handler linked into the main executable, and will not be able to call handle_http(). Contrast this with what happens when you link as:
g++ main.cc -Wl,--whole-archive -lhttp -Wl,--no-whole-archive -lhandlers
The same "self registration" style is also possible in plain-C, e.g. with the __attribute__((constructor)) GNU extension.
Another legitimate use for --whole-archive is for toolkit developers to distribute libraries containing multiple features in a single static library. In this case, the provider has no idea what parts of the library will be used by the consumer and therefore must include everything.
An additional good scenario in which --whole-archive is well-used is when dealing with static libraries and incremental linking.
Let us suppose that:
libA implements the a() and b() functions.
Some portion of the program has to be linked against libA only, e.g. due to some function wrapping using --wrap (a classical example is malloc)
libC implements the c() functions and uses a()
the final program uses a() and c()
Incremental linking steps could be:
ld -r -o step1.o module1.o --wrap malloc --whole-archive -lA
ld -r -o step2.o step1.o module2.o --whole-archive -lC
cc step3.o module3.o -o program
Failing to insert --whole-archive would strip function c() which is anyhow used by program, preventing the correct compilation process.
Of course, this is a particular corner case in which incremental linking must be done to avoid wrapping all calls to malloc in all modules, but is a case which is successfully supported by --whole-archive.
I agree that using —whole-archive to build executables is probably not what you want (due to linking in unneeded code and creating bloated software). If they had a good reason to do so they should have documented it in the build system, as now you are left to guessing.
As to your second part of the question. If an executable links both a static library and a dynamic library that has (in part) the same object code as the static library then the —whole-archive will ensure that at link time the code from the static library is preferred. This is usually what you want when you do static linking.
Old query, but on your first question ("Why"), I've seen --whole-archive used for in-house libraries as well, primarily to sidestep circular references between those libraries. It tends to hide poor architecture of the libraries, so I'd not recommend it. However it's a fast way of getting a quick trial working.
For your second query, if the same symbol was present in a shared object and a static library, the linker will satisfy the reference with whichever library it meets first.
If the shared library and static library have an exact sharing of code, this may all just work. But where the shared library and the static library have different implementations of the same symbols, your program will still compile but will behave differently based on the order of libraries.
Forcing all symbols to be loaded from the static library is one way of removing confusion as to what is loaded from where. But in general this sounds like solving the wrong problem; you mostly won't want the same symbols in different libraries.

Resources