简体   繁体   中英

How to add widget in layout if there is available place for it? Otherwise not to add

In my program I must show information (MarketWidgets with different size) divided in some pages (MarketWidgetsList that hold list of MarketWidgets). My first approach was to add widgets while there is available place for that widget, and if there isn't place another page must be created and add widget to that page. Is it an acceptable approach? To get widget's size I'm using QWidget::sizeHint() because the widget still isn't painted, but it seems not correct. Can sizeHint return not exact size if I'm using stretch in layout?
Is there a way to add widget in layout if layout can show widget normally otherwise somehow indicate that there is not enough space?

code example

bool  Ui::DynamicMarketsWidget::add_group_market_widget(Ui::GroupMarketWidget *dynamic_group_market_widget)
{ 
    Q_ASSERT(dynamic_group_market_widget); 
    int tmp_height = dynamic_group_market_widget->sizeHint().height();                                     if(m_available_height > tmp_height) 
    { 
        m_market_layout->addWidget(dynamic_group_market_widget); 
        m_available_height -= tmp_height; 
        return true; 
    } 
    return false; 
}

The method sizeHint() returns the 'optimal' or 'desired' size of a widget. If a widget is assigned to a layout it does not necessarily have this size. The size the widget currently actually has can be obtained by calling the methods size() , width() or height() .

You could try to update your m_available_height with this value instead of the value obtained by the size hint method. Just make sure you assign your widget first before reading the size.

You could try something like this:

bool  Ui::DynamicMarketsWidget::add_group_market_widget(Ui::GroupMarketWidget *dynamic_group_market_widget)
{ 
    Q_ASSERT(dynamic_group_market_widget); 
    int tmp_height = dynamic_group_market_widget->sizeHint().height();                                     if(m_available_height > tmp_height) 
    { 
        m_market_layout->addWidget(dynamic_group_market_widget); 
        m_available_height -= dynamic_group_market_widget->height(); 
        return true; 
    } 
    return false; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM