1

我有一个从 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);

有什么想法可以在这里发生吗?

4

2 回答 2

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

PS当心std::auto_ptr,你可能想使用std::unique_ptr这些天。

于 2013-08-18T19:43:03.543 回答
1

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

问候,

于 2013-08-18T19:40:01.317 回答