Pointers in C++ Class are getting scrambled - c++

I've got a lot of code that's driving me really crazy right now.
I'm working with OpenGL, building a GUI framework which utilizes several different types of objects. I have Image classes which load *.png files and store image information in the form of a GLuint texture reference. I have Panel and Button classes with pointers to the image classes they should be displaying. I have a Hud class with std::vectors of Panel and Button pointers. Finally, I have an Engine class that contains one Hud class, all my Button and Panel classes, and Image pointers. When the constructor is run, each of the Image pointers is initialized using:
imgMy = new Image;
Once all the images have been initialized, I run my load functions:
imgMy->loadImage("imgMy.png");
Of course, I delete the Images when I close the program.
My problem is that some of the images are getting "crossed." I have about thirty images right now, and a couple of the buttons are apparently pointing to the wrong images. I have checked my code thoroughly, and it appears to be solid. I believe this is a memory bug since the buttons which display the incorrect images are inconsistent. Sometimes they display the correct images, sometimes different buttons are displaying the wrong images. I wish I could show my code here, but it's pretty massive.
The reason I'm using Image pointers in my Engine class instead of actual Image objects is that I'm afraid of the Buttons pointing to invalid memory if the Engine class is resized, or its memory rearranged. I suspect there's a much better approach to what I'm trying to accomplish, and I'd appreciate any advice along those lines.

Use a debugger that lets you put a watchpoint on the relevant imgMys, and then the debugger will tell you where they're being modified. That is probably the easiest way to track it down.
You may also want to try valgrind, but this doesn't sound like the type of problem valgrind will find.

Firstly, you should not use two-phase initialization without a really good reason. This is not a really good reason. Pass the filename in the constructor. Also, always use smart pointers.
You could simply use const to enforce it.
class Button {
const std::unique_ptr<Image> img;
public:
Button(std::string filename)
: img(new Image(filename)) {}
};
Secondly, I don't quite grok your overriding architecture, as you don't describe it in any real detail, but I'm unsure of the need of new here.

Sounds like memory corruption. You should consider using some memory debugger like valgrind or some other alternative. If you have any issues using pointers, those tools will help you track them down.

I suspect that you're keeping a list of button references and a list of image references somehow and that they are not always created in the same order, hence the cross over images.
Strictly speaking you should create your a button and it's image in order, assigning the image file at creation time.

Related

Qt | creating a dynamic object in a customized scene

Good day to all!
I would like to learn from the respected community how it is possible using Qt Designer to create a simple GUI that performs what is shown in the attached image. Namely: after a single click of the LMB, a marker is placed at the place of the click, indicating the beginning of the polygon, and a temporary polygon of the desired type (but of different sizes) begins to follow the mouse cursor until we click on the LMB again, after which the final polygon will be built from the point of the first click of the LMB to the point of the second click. Such a ready-made polygon will have to be stored somewhere in memory for further work with it.
As a polygon here, I show a complex sector built on some calculated points, but as a simple example, you can take a straight line - I don't think that the essence of the program changes much.
I have already looked at many examples of different implementations of different things on QGraphicsScene, but I could not figure out exactly how to create an object in the way I needed. That is, I know that we need a separate class describing the polygon and calculating the coordinates of which it consists, but I don't quite understand how to implement the dynamics - with each mousemoveivent, delete the temporary polygon and draw a new one for the new coordinates, or how?
P.S. If it won't be so difficult, could someone also show how to implement what was conceived through the redefined paintScene class, replacing the standard QGraphicsScene class and inheriting from it? I am faced with the fact that when creating a custom class of the scene object, clicking on the objects attached to it is ignored by the program, and instead of, for example, dragging an object on the scene when clicking on it, the mousePressEvent of the scene, not the object, is triggered, and I do not understand what the problem is.
P.P.S. I apologize for my English and thank everyone for any help!

Why a layout is required for multiple widgets recieving events?

I'm actually writing a module in qt (container) inerhiting from QWidget which is containing multiple plots presenting a graph where all of them inerhit from QWidget.
So it's given:
1 container can have :
n plots where each of them contains
1 graph.
I had yesterday a lot of time spent for figuring out a bug.
It happened that just the n plots which were (for debug purposes) added to the container in its constructor to catch the paint events.
All plots that were added by the same method while the container was constructed allready, were not able to receive any events.
later on, a coworker after I requested assistance explained me, that my container (which is located in the mainwindow-form) needs to get asigned a layout in the Qtdesigner. I gave it a try and was suprised that it did solve my problem. After adding the dynamicly generated plots to the container and aswell adding them to the layout, all widgets were receiving the events as expected.
But since I wasn't able to understand his explanation and don't want to bother him with it further, I'm asking it here.
So why dynmacially generated widgets which are child objects of other dynamically generated QWidgets require the parent which is a child of the mainwindow to have a layout asigned?
And if this is not just a exceptional case, why it isn't asigned by default and additional I wasn't able to find cases on the web, of tohers having such problems?
You're likely seeing the side effects of overlapping sibling widgets, or perhaps widgets having zero size. All that a layout does is resize them and ensure they don't overlap.
added to the container in its constructor to catch the paint events
What do you mean by "cathing" the paint events and what has that got to do with any constructors? You claim that all of your classes (the container, the plot, and the graph) derive from QWidget. They should all implement paintEvent, unless they are designed to have no content of their own other than a default background brush.
I imagine that you're somehow complicating things too much, but without self contained piece of code that we can compile to replicate your problem, we'll be going around in circles. Feel free to look around in my answers: they all consist of a single main.cpp, sometimes with quite a bit of functionality squeezed in. Almost universally, there's no code other than necessary to demonstrate a given technique. Your question should include similarly minimized, compileable example.

Managing layouts in Qt with "empty" widgets for displaying images

I am designing a GUI in Qt that has placeholders for a number of images (images will be set and updated at run time) along with some input fields (QLineEdits with QLabels grouped into QGroupBoxes). I am using a technique similar to the answer here:
How do I make an image resize to scale in Qt?
for the image display widgets. Some are a class that inherits from QWidget that can draw an aspect-scaled image, others are a class that inherits from QLabel that can do the same and also display text. These are custom C++ classes.
The problem I am having is with the layout and getting things spaced correctly. I am using Qt Designer to layout the GUI. Since the image widgets are "empty" they don't exert a lot of "force" on the other widgets and the other widgets tend to dominate even though I don't need the other widgets to be that big. The QLineEdits especially like to be as wide as they can be. I want to GUI to be adaptable for different sizes (to accommodate different screen resolutions) so I don't really want to set a lot of sizes manually if I can help it.
I do not have a lot of experience in Qt and managing layouts. What I know I have mostly learned from playing around with it. I have tried searching for similar situations without much success. I can't figure out the terms to use for my specific situation. Does anyone have any suggestions for what I can do to better control the layout? Alternatively, are there any good resources for learning how to manage Qt's layouts? The Qt documentation I have looked at is fairly basic. There are a lot of options, most of which I am unsure exactly how they should work, and the trial-and-error approach is getting to be too cumbersome for more complex layouts.
I am using Qt 4.8.
Sorry to be vague. This is a work project and I would rather not post exactly what I have. And coming up with a generic example will take time. I think my questions are generic enough that it shouldn't matter. If a more specific example is needed, I can try to throw something together.
Edit:
Here is what the layout looks like in Designer right now. The black boxes are redacted labels. The orange boxes are where images will go. The one in the top-left corner is a particular problem. I currently have the top and bottom halves on the left in a splitter in an effort to make things fit better. I think that may be making it worse.
http://i.stack.imgur.com/nRRg3.png (long-time reader, first-time poster :-/)
Making the "What I want it to look like" picture is going to take a bit longer. It may be easy to see what I don't like. The input fields need to be much smaller to make room for the images.
Edit2:
And here's something closer to what I would like. The upper-left and right-hand images are larger and actually visible. I might like the boxes in the lower-middle to be even bigger, but there's only so much room. If I can get the layout right, I'm hoping that will optimize the size of everything for a given window size.
http://i.stack.imgur.com/yvLvi.png

Best Practice in Cocos2d

I am at the start of my cocos2d adventure, and have some ideological questions to ask. I am making a small space-shooter game, am I right to use the following class structure?
Scene
Background Layer
Infinite parallax background
Game Layer
Space ships
Bullets
Control Layer
Joystick
Buttons
and a followup question — what is the best practice in accessing objects from other layers? For example, when the joystick is updated, it must rotate the space ship and move the background. Both of these are in other layers. Is there some recommended way to go about this or should I simply get the desired objects by Tag and operate on them?
Cocos is a big singleton-based system, which may not appeal to some developers but is often used in Cocos apps and is the fundamental architecture of the framework. If you have one main scene and many subsequent layers added to that scene, and you want controls from one layer to affect sprites or logic on other layers, there really is nothing wrong with making your main scene a singleton and sending the information from the joystick layer back to the scene to handle for manipulating other layers or sprites. I do this all the the time and this technique is used in countless Cocos tutorials in books and online, so you can feel that you aren't breaking too many rules if you do it this way (and it's also quite easy to do).
If you instead choose to use pointers in one layer to send data to other layers, this can get you into a lot of trouble since one node should never own another node that it doesn't have a specific parent-child relationship with. Doing so can cause crashes and problems with the native Cocos cleanup methods when you remove scenes later, and potentially leak memory. You could use a weak reference in such a case instead, but that is still dependent on one layer expecting another layer to always be around, which may not be the case.
Sending data back to the main game scene to then dispatch and use accordingly is really efficient.
This seems like a perfectly reasonable way to arrange your objects, this is a method I use.
For accessing objects, I would keep an explicit reference to the object as a member variable and use it directly. (Using tags isn't a bad option, I just find it can get a little messy).
#interface Class1 : NSObject
{
CCLayer *backgroundLayer;
CCLayer *contentLayer;
CCLayer *hudLayer;
CCSprite *objectIMayNeedToUseOnBackgroundLayer;
CCNode *objectIMayNeedToUseOnContentLayer;
}
Regarding tags, one method I use to make sure the tag numbers I'm assigning are unique is define an enum as follows:
typedef enum
{
kTag_BackgroundLayer = 100,
kTag_BackgroundImage,
kTag_GameLayer = 200,
kTag_BadGuy,
kTag_GoodGuy,
kTag_Obstacle,
kTag_ControlLayer = 300
kTag_Joystick,
kTag_Buttons
};
Most times I'll also just set zOrder and tag properties of CCNodes (i.e. CCSprites, CCLabelTTFs, etc.) the same, so you can actually use the enum to define your zOrder, too.

QT Creator c++ writing Kakuro puzzle and unsure of what widget to use

I'm using QT creator and have all my methods etc designed and trying to design a UI and I'm not sure what widget I should be using to reference my puzzle layout.
I've been reading over the documentation for a while and I still am nowhere closer to finding a solution to what I should be using to display my values. I know what I should like but all I seem to find information on is various layouts of entry boxes that are in no way linked. I have no problem with coding it myself to communicate with my classes if I just knew what to use to start off with.
I need something that can help me create a layout that has up to two numbers with positions specific to the type of hint it is with a slash between the hints, black blocks that are neither hints nor stored values and squares that have values that can take up the whole square.
Layout is something similar to http://www.nikoli.co.jp/en/puzzles/kakuro/
I wish I knew what to pick >.<
Personally I'd use QGraphicsView and handle the drawing myself.
It can draw rectangles, triangles, circles and text without much effort, and that's pretty much everything you need as far as I can see. You just need to add the objects to a QGraphicsScene and you get them on the screen. You can also interact with the objects (you can find which object you're pointing at etc.)