1
votes

The application that I'm building is supposed to create, destroy, and manipluate widgets that I've created

The problem is I'm not making a simple program with nice buttons where everything is symmetrical and needs to be evenly spaced and handled via a layout that will automatically move everything around and space it. And yet, the only way I know of is to manually instance a layout and add the widgets to it, but then I can't set the coordinates of them

How can I simply instance my widget, and add it to the project generated frame? This is how I'm instantiating my class, in which case I then set my own parameters:

            Tile *tile = new Tile;
            tile->setImg("://Images/placeholderTile.png");
            tile->setCol(true);
            tile->setGeometry(retX(line),retY(line),50,50);

To reiterate, I want to add my own widgets to a frame outside of the editor (only by code), and be able to manually move them around the frame by code. I don't see an ".addWidget() as a method accessible from the QFrame, and yet they can be children within the designer, why can't I do this by code? Whenever I try to do it manually and add them to any layout, any attempt I make to manually set the widgets location doesn't do anything. I haven't overridden the setGeometry

I fixed my problem After 2 hours of continual searching I finally came across my answer I never thought that you could set the parent of a widget by code, as I thought you strictly had to add it in as a child of something else, not the reverse and declare that it should have a parent

So, by simply adding the line:

            tile->setParent(ui->frame);

completely fixed my problem. I will change this post back and submit the answer tomorrow when I'm allowed to by this site.

Thank you to those who actually came though. I'm just glad I managed to fix it before that.

1
I fixed my problem. However I can't submit it as an answer due to low rep so I will just append it to my question.Yattabyte

1 Answers

2
votes

All you need is to pass the parent to the widget's constructor:

Tile *tile = new Tile(ui->frame); // <-- here
tile->setImg("://Images/placeholderTile.png");
tile->setCol(true);
tile->setGeometry(retX(line),retY(line),50,50);

Since Tile is your own class, you should definitely have a Qt-style, parent-taking explicit constructor for it:

class Tile : public QWidget {
  ...
public:
  explicit Tile(QWidget * parent = 0) : QWidget(parent) { ... }
};

Another approach is to write your own layout that would know about the relationships that are to be held between your objects. After you do it once, writing custom layouts isn't that hard.