問(wèn)題描述
我想在 Qt 中創(chuàng)建一個(gè)具有以下功能的自定義小部件:
I would like to create a custom widget in Qt with the following features:
- 這是一個(gè)容器
- 它可以填充任何 Qt 布局
- 它可以在任何 Qt 布局中
- 按鈕允許垂直折疊/折疊內(nèi)容,因此只有按鈕可見(jiàn),所有包含的布局都不可見(jiàn).
- 上一個(gè)按鈕允許將其再次展開(kāi)/展開(kāi)到布局內(nèi)容的大小.
- 展開(kāi)/折疊基于尺寸(不是顯示/隱藏)以允許動(dòng)畫(huà).
- 可在 QDesigner 中使用
為了提供一個(gè)想法,這是一個(gè)類(lèi)似小部件(不是 Qt)的圖像:
To provide an idea, here is an image of a similar widget (not Qt):
我已經(jīng)有一個(gè)框架可以正常工作并在 QDesigner 中公開(kāi).我現(xiàn)在需要讓它展開(kāi)/折疊,這看起來(lái)并不那么簡(jiǎn)單.
I already have a frame that work correctly and is exposed in QDesigner. I need now to make it to extend/collapse, which does not seem so simple.
我嘗試使用 resize()、sizePolicy()、sizeHint() 但這不起作用:當(dāng)框架折疊時(shí),我得到以下值:
I tried to play with resize(), sizePolicy(), sizeHint() but that does not work: When the frame is collapsed I got following values:
QLayout::closestAcceptableSize 不是小部件的一部分,因此我無(wú)法更改它.
QLayout::closestAcceptableSize is not part of the widget so I cannot change it.
任何提示或/和代碼片段來(lái)實(shí)現(xiàn)這一點(diǎn)?
這里有一個(gè)簡(jiǎn)單的例子.除必要外,我刪除了所有內(nèi)容.
EDITED: Here a simple example. I removed all except necessary.
main.cpp 示例
main.cpp example
Section.hpp
Section.hpp
推薦答案
我偶然發(fā)現(xiàn)了同樣的問(wèn)題,并通過(guò)將可折疊小部件實(shí)現(xiàn)為 QScrollArea
來(lái)解決它,其最大高度由 動(dòng)畫(huà)>QPropertyAnimation
.
I stumbled upon the same problem and solved it by implementing the collapsible widget as a QScrollArea
whose maximum height is animated by a QPropertyAnimation
.
但因?yàn)槲也皇褂?QDesigner,所以我不能告訴你它是否在那里工作.
But since I don't use QDesigner, I can't tell you if it works there.
我仍然有一個(gè)問(wèn)題:可折疊小部件不僅可以向底部方向擴(kuò)展,還可以向頂部和底部擴(kuò)展.如果尚未達(dá)到其最小高度,這可能會(huì)導(dǎo)致位于其上方的小部件縮小.但這與我們必須自己構(gòu)建這個(gè)東西的事實(shí)相比確實(shí)是一個(gè)細(xì)節(jié)......
I still have one problem: Instead of only expanding towards the bottom direction, the collapsible widget can expand towards the top and bottom. This can cause widgets located above it to shrink if they haven't reached their minimum height, yet. But this is really a detail compared to the fact that we have to build this thing ourselves…
Spoiler.h
Spoiler.cpp
如何使用:
這篇關(guān)于如何在 Qt 中制作可展開(kāi)/可折疊的部分小部件的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!