Solved Why doesn't this widget initialization work?
-
I tried the "Child Widgets" tutorial, and I thought I would be able to create a child pushbutton by doing direct initialization rather than creating a pointer. In the code below, I commented out the pointer lines and replaced them with direct initialization lines. When I tried to build, however, on the initialization line I get the error "cannot access private member declared in class 'QPushButton'". Why is this error called when I try direct initialization? I'm pretty sure I'm following the right syntax. Is it just a Qt rule that I must use pointers to work with widgets?
#include <QtWidgets> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget window; window.resize(320, 340); window.show(); window.setToolTip("This is the Top-level widget"); window.setWindowTitle(QApplication::translate("toplevel", "Top-level widget")); /*QPushButton button = new QPushButton(QApplication::translate("pushbutton", "Test Push"), &window); button -> show(); button -> move(100, 100); */ QPushButton button(QPushButton(QApplication::translate("pushbutton", "Test Push"), &window)); //error is here button.show(); button.move(100,100); return app.exec();
}
-
Hi,
@DragonautX said in Why doesn't this widget initialization work?:
Why is this error called when I try direct initialization?
This has nothing to do with the stack allocation. The problem is that you're invoking the copy constructor of the
QPushButton
class and as allQObject
descendants the copy constructor is made private (copying is forbidden). Here's the long story why.If you remove the (unnecessary) copying for your push button, e.g.:
QPushButton button(QApplication::translate("pushbutton", "Test Push"), &window);
you should get a clean build.
Is it just a Qt rule that I must use pointers to work with widgets?
There's no such rule. Stack allocation is perfectly fine, and in my opinion a 'zillion times better than creating on the heap with
new
.Kind regards.
-
Oh, thanks. I didn't even notice I called QPushButton twice. That was never my intention. Anyways, thanks for the code check. The link is helpful too.