当显示为对话框时,派生窗口小部件不以父窗口为中心

时间:2013-08-18 17:49:49

标签: c++ qt qdialog

我有一个来自QWidget的MyListWidget类。我将parent和flags传递给基类QWidget构造函数(在测试中尝试了Qt :: Dialog和Qt :: Popup),但是自定义小部件显示在屏幕中央,而不是以其父级为中心。

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

这是构造函数:

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

如果我把这个小部件放到一个单独的对话框中,任何东西都按预期工作。但为什么呢?

包装工作:

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);

任何想法可能会发生在这里?

2 个答案:

答案 0 :(得分:5)

默认情况下,

QWidget未显示在中心,因此您需要手动居中(您可以在构造函数中执行此操作):

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。谨防std::auto_ptr,您最近可能想要使用std::unique_ptr

答案 1 :(得分:1)

我不太确定你想要实现的目标,但我觉得你应该从QDialog派生MyListWidget。

此致

相关问题