当显示为对话框时,Derrived Widget不在父对象的中心 [英] Derrived Widget not centered on parent when shown as dialog

查看:219
本文介绍了当显示为对话框时,Derrived Widget不在父对象的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类MyListWidget从QWidget派生。我将父类和标志传递给基类QWidget构造函数(在测试中同时尝试了Qt :: Dialog和Qt :: Popup),但自定义窗口部件显示在屏幕中心,而不是以其父对象为中心。

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

这是构造函数:

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?

包装工作:

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?

推荐答案

默认情况下不会在中心显示QWidget ,所以你需要手动集中它(你可以在构造函数中)

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

注意 std :: auto_ptr ,这些天你可能想使用 std :: unique_ptr

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

这篇关于当显示为对话框时,Derrived Widget不在父对象的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆