[SOLVED] Centering a dynamically created custom widget?



  • I'm using the answer to this "SO question":http://stackoverflow.com/a/14107727/840992 to make a custom image widget which automatically scales correctly. It works fine but now I am trying to center the image widget instance at the center of my main window.

    My idea was to create a QHBoxLayout, add the image widget to that and then add the hBox instance to the ui->verticalLayout.

    Doesn't work. The image still displays flush left.

    I then tried a few variations on 'setAlignment` for both/either the QHBoxLayout and the QVBoxLayout but then the image doesn't appear at all. My simple test code is below.

    What am I missing here?

    @
    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);

        QPixmap pix;
        pix.load("/Users/home/Desktop/test.jpg");
        
        ImageLabel2* image = new ImageLabel2(this);
        image->setPixmap(pix);
        
        QHBoxLayout* hbox = new QHBoxLayout();
        hbox->addWidget(image);
    
        //    hbox->setAlignment(image,Qt::AlignCenter);
    
        hbox->setAlignment(Qt::AlignHCenter);
    
        //    ui->verticalLayout->addLayout(hbox);
    
        ui->verticalLayout->addLayout(hbox);
    
        //    ui->verticalLayout->addWidget(image);
        //    ui->verticalLayout->setAlignment(image,Qt::AlignCenter);
        //    ui->verticalLayout->setAlignment(Qt::AlignHCenter);
        
    }@

  • Moderators

    To be honest this first SO answer is bad. Please don't use it.
    The second one (with paintEvent) is ok, but needs a modification to center the image:
    @
    class CustomWidget : public QWidget {
    public:
    CustomWidget(const QPixmap &p, QWidget* parent = 0)
    : QWidget(parent), pixmap(p) {}

    void paintEvent(QPaintEvent * e)
    {
        QRect srcRect(QPoint(), pixmap.size());
        QSize dstSize = srcRect.size().scaled(
              e->rect().size(), Qt::KeepAspectRatio);
        QRect dstRect(QPoint((width() - dstSize.width())/2,
                             (height() - dstSize.height())/2), dstSize);
    
        QPainter p(this);
        p.setRenderHint(QPainter::Antialiasing);
        p.drawPixmap(dstRect, pixmap, srcRect);
    }
    

    private:
    QPixmap pixmap;
    };
    @
    and then in the main window:
    @
    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);
    setCentralWidget(new CustomWidget(QPixmap("test.png")));
    }
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.