Custom widget size adaptive in QListWidget

background:

item in QListWidget, you can addcustom widget.

ButHow to adjust the size of the widget?

Reference:QT QListWidget addition and deletion, scroll bar display or hiding, judging whether to slide to the top or bottom, and making QListWidgetItem adaptive size_qlistwidgetitem adaptive height-CSDN Blog

How to usedaigo

void listwidgetItem::resize_size()
{
	adjustSize();
	if (item != nullptr) {
		item->setSizeHint(this->size());
	}
}

adjustSize() is used toadjust the size of the custom widget.

item is a QListWidgetItem bound to a custom widget, and its size also needs to be adjusted.

The following is a custom widget, which needs to adapt to different heights according to different word counts.

Effect: 

 

At this time, I found that the following green QLabel was not adaptive.

Very disturbing. (The problem was solved later, but I don’t understand it, so I’ll record it here)

Turn on debug mode:

void listwidgetItem::resize_size()
{
	adjustSize();
	if (item != nullptr) {
		item->setSizeHint(this->size());
	}
	if (this->name == QString::fromLocal8Bit("联想应用商店")) {
		PRINTF_LOCATION() << this->name << "   " << this->height();
		PRINTF_LOCATION() << "sizehint():"<<label_introduce->sizeHint();
		PRINTF_LOCATION() << "size():"<<label_introduce->size();
	}
}

At the beginning: 

d:\work\С????\main\officeassistant_msvc\listwidgetitem.cpp  at: 22 : sizehint(): QSize(720, 270)
d:\work\С????\main\officeassistant_msvc\listwidgetitem.cpp  at: 23 : size(): QSize(574, 275)

Drag the form later: 

d:\work\С????\main\officeassistant_msvc\listwidgetitem.cpp  at: 22 : sizehint(): QSize(720, 270)
d:\work\С????\main\officeassistant_msvc\listwidgetitem.cpp  at: 23 : size(): QSize(1263, 270)
d:\work\С????\main\officeassistant_msvc\listwidgetitem.cpp  at: 22 : sizehint(): QSize(720, 270)
d:\work\С????\main\officeassistant_msvc\listwidgetitem.cpp  at: 23 : size(): QSize(1263, 270)

You can find that the sizehint() of label has always been QSize(720,270), and height is also 270.

Solution:

Add to:

label_introduce->setFixedWidth(this->width() - 50);

void listwidgetItem::resize_size()
{
	label_introduce->setFixedWidth(this->width() - 50);
	adjustSize();
	if (item != nullptr) {
		item->setSizeHint(this->size());
	}
	if (this->name == QString::fromLocal8Bit("联想应用商店")) {
		PRINTF_LOCATION() << this->name << "   " << this->height();
		PRINTF_LOCATION() << "sizehint():"<<label_introduce->sizeHint();
		PRINTF_LOCATION() << "size():"<<label_introduce->size();
	}
}

 The text content has been modified, but it does not affect it.

At the end of writing, the page effect has reached my expectations, but I don’t quite understand the process in the middle, so I’ll record it here.

Guess you like

Origin blog.csdn.net/weixin_51883798/article/details/134712257