QListView から拡張された展開可能な ListView を作成しました。ヘッダー データ (展開されていないアイテム) を表示したいだけの場合はすべてうまく機能します。ハードコードされた高さ 64 を指定したためです。展開すると詳細が表示されます。アイテム。しかし、問題は、詳細が 1 行以上になる可能性があるため、詳細の正確な高さがわからないことです。アイテムの内容に応じてアイテムの高さを合わせたいと考えています。
アイテムの展開または折りたたみ時にクリック リスナーを処理するコードは次のとおりです。
LogListItemDelegate *delegate = static_cast<LogListItemDelegate *>(itemDelegate());
QStandardItem *item = static_cast<QStandardItemModel *>(model())->itemFromIndex(index);
bool expand = delegate->isExpandable() && mapFromGlobal(QCursor::pos()).x() >= visualRect(index).width() - 48;
bool expanded = index.data(LogListItemDelegate::DT_Expanded).toBool();
// here the height returned is header height, no containing the details which it is in expanding mode
int height = item->sizeHint().height();
if (!expanded) {
item->setData(true, LogListItemDelegate::DT_Expanded);
item->setSizeHint(QSize(0, 150)); // 150 here must be dynamically calculated
} else {
item->setData(false, LogListItemDelegate::DT_Expanded);
item->setSizeHint(QSize(0, 64)); // 64 is the header height, no prolem
}
問題は、アイテムが展開されたときの高さを計算する方法です。
結果:
編集:
It is when I want to add the message to the list
void LogListView::addMessage(const QJsonObject &msg, const bool append)
{
static int id = 1; // unique id for log items
auto *item = new QStandardItem();
item->setEditable(false);
item->setData(QString("%1").arg(id++, 5, 10, QChar('0')), LogListItemDelegate::DT_Id);
item->setData(msg["icon"], LogListItemDelegate::DT_ICON);
item->setData(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"), LogListItemDelegate::DT_Timestamp);
item->setData(msg["title"], LogListItemDelegate::DT_Title);
item->setData(msg["subtitle"], LogListItemDelegate::DT_Subtitle);
item->setData(msg["details"], LogListItemDelegate::DT_Details);
item->setData(false, LogListItemDelegate::DT_Expanded);
// here I am unable to calculate the height, because the details does not have a specific height to set here,
// so when append the item to the list it is unvisible. If set the height 64, it is the exact height of the item without details, which is good
//item->setSizeHint(QSize(0, 64));
static_cast<QStandardItemModel *>(model())->appendRow(item);
scrollToBottom();
}
sizeHint()内のコードです
QSize LogListItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
bool expanded = index.data(DT_Expanded).toBool();
QFont fntDetials = option.font;
fntDetials.setPointSize(12);
QRect r = option.rect;
QFontMetrics fm(fntDetials);
QString details = index.data(DT_Details).toString();
QRect br = fm.boundingRect(r, Qt::TextWordWrap, details);
return QSize(option.rect.width(), br.height()+64);
}
残念ながら動作しません.... Qt は Android の ListView とそのリサイクル機能を見て ListView の問題を解決できると思います。