我有一个从 QWidget 派生的类 MyListWidget。我将父级和标志传递给基类 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);
你知道这里会发生什么吗?
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()
);
}
附:提防std::auto_ptr
,你可能想使用std::unique_ptr
这些日子。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)