Derrived Widget not centered on parent when shown as dialog

余生长醉 提交于 2019-12-02 13:51:53

问题


I have a class MyListWidget derrived from QWidget. I passed parent and flags to the base class QWidget constructor (tried both Qt::Dialog and Qt::Popup in tests) but the custom widget is shown in the center of the screen instead centered to its parent.

MyListWidget* myListWidget = new MyListWidget(this, Qt::Dialog);

This is the constructor:

MyListWidget::MyListWidget(QWidget* parent, Qt::WindowFlags flags)
    : QWidget(parent, flags),
      ui(std::auto_ptr<Ui::MyListWidget>(new Ui::MyListWidget))
{
    ui->setupUi(this);
}

If I put this widget into a separate dialog, anything works as expected. But why?

Wrapping works:

QDialog* popup = new QDialog(this, Qt::Popup);
QVBoxLayout* hLayout = new QVBoxLayout(popup);

// ... doing list creation like above

hLayout->addWidget(mmyListWidget);
popup->setLayout(hLayout);
const int width = mapListWidget->width();
const int height = mapListWidget->height();
popup->resize(width, height);

Any ideas what could happend here?


回答1:


QWidget is not shown on center by default, so you need to center it manually (you can do that in the constructor):

MyListWidget::MyListWidget(QWidget* parent, Qt::WindowFlags flags)
    : QWidget(parent, flags),
      ui(std::auto_ptr<Ui::MyListWidget>(new Ui::MyListWidget))
{
    ui->setupUi(this);
    move(
       parent->window()->frameGeometry().topLeft() +
       parent->window()->rect().center() - rect().center()
    );
}

P.S. Beware of std::auto_ptr, you probably want to use std::unique_ptr these days.




回答2:


I'm not quite sure what you're trying to achieve but I have the feeling you should derive MyListWidget from QDialog.

Regards,

Ben



来源:https://stackoverflow.com/questions/18302025/derrived-widget-not-centered-on-parent-when-shown-as-dialog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!