Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Programatically adding custom widget to a layout



  • I created a custom class that extends QWidget and uses the Q_OBJECT macro to accomodate some custom signals / slots. I tested my class in a simple stand alone program and it works fine (I use it to add pan / zoom capability to a pix-viewer). Now I want to add to a large program that I've already developed (I want to remove a label object that used to display images and swap it out with my new thing.).

    So, I proceeded slowly. First I just wanted to confirm I could programmatically add a widget where I wanted it. This works fine:

        QPushButton *b1 = new QPushButton("A");
        QHBoxLayout *hLayout = new QHBoxLayout;
        hLayout->addWidget(b1);
        ui->scrollArea_3->setLayout(hLayout);
    

    Cool. So now I just think I can swap out that plain old button with my widget, but this chokes:

        ImageViewer *b1 = new ImageViewer();
        QHBoxLayout *hLayout = new QHBoxLayout;
        hLayout->addWidget(b1);
        ui->scrollArea_3->setLayout(hLayout);
    

    ImageViewer is my custom class. The really odd thing is how this chokes. I start getting this error:

    Capture.PNG

    The really strange thing is that after I switch back to the QPushButton version that worked before .. I get the same error (winnt.h) ..... Even if I clean the project and rebuild the error persists. It seems that I need to completely restore my project to get back to where I was. I'm very confused.

    Here's how my custom class starts .. but I feel that my problem is much more fundamental (do I need to cast it as a different kind of widget / Q_object before stuffing it into a layout? And even if that's the case why does it seem to break my entire project?)

    #ifndef IMAGEVIEWER_H
    #define IMAGEVIEWER_H
    #include <QtWidgets>
    
    
    class ImageViewer : public QWidget
    {
    
        Q_OBJECT
    
    
    public:
        ImageViewer();
        .....
    

  • Lifetime Qt Champion

    @amess Please provide the whole error message, so we can see from where it originates.



  • Here is the error (first one points to line 568. So odd.

    8e4c8dc5-a189-4edf-8070-358513c8e3e7-image.png



  • This post is deleted!


  • OK, solved. My code posted is fine as is. I was using a 3rd party SDK that redefined TCHAR which set off an unfortunate chain of events. I think as long as you make a class that extends QWidget the code in my example is a perfectly fine way of plopping it in the GUI.


Log in to reply