當我們使用QScrollArea向里面添加控件時,希望顯示到最近添加的那個控件或者顯示指定的控件
ui.scrollArea->ensureWidgetVisible(childWidget);
但是當動態添加控件后
-
buttons.append(new QPushButton("New button",scrollAreaWidgetContents_2));
-
buttons[buttons.count()-1]->setGeometry( QRect(80, 330, 112, 26));
-
horizontalLayout_2->addWidget(buttons[buttons.count()-1]); //Add the new element and it is show in the screen
-
//How to move to this new element?
-
scrollArea->ensureWidgetVisible(buttons[buttons.count()-1],0,0); //This does not work
發現並不會顯示到新加的控件,是因為添加完新控件scrollArea會調整期大小導致后面語句不生效
qApp->processEvents()
scrollArea->ensureWidgetVisible(buttons[buttons.count()-1],0,0);
再設置ensureWidgetVisible前面加上這個qApp->processEvents(),基本能解決問題
如果還是有問題
qApp->processEvents()
qApp->processEvents()
scrollArea->ensureWidgetVisible(buttons[buttons.count()-1],0,0)
我這邊就加兩邊才精確定位到到顯示的子控件
這里面有好多知識點
參考網址:https://www.qtcentre.org/threads/30632-QScrollArea-Scroll-to-widget-problem