2013-08-18 15 views
1

我有一個從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); 

任何想法可能在這裏happend?

回答

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

附:當心std::auto_ptr,您現在可能想要使用std::unique_ptr

1

我不太清楚你想達到什麼,但我有這種感覺,你應該從QDialog派生MyListWidget。

問候,

相關問題