QListView
我遇到了一些问题。我想为这个对象添加一个标题。但是,我找不到执行此类任务的方法。我在SO和Qt论坛上看过几篇帖子,但没有发现任何与我的需求相关的帖子。我记得,在过去,我使用了一些可以适应QListView
的东西(我认为它的灵感来自Qt例子,但不记得是哪一个)。
对于那些需要在QListView
顶部显示标题的人,我会在此处发布代码。如果有人发现虚假或不适应的东西,请告诉我。这是代码:
class MainMenuListView : public QListView
{
Q_OBJECT
class Header : public QWidget
{
public:
Header(MainMenuListView* parent);
QSize sizeHint() const;
protected:
void paintEvent(QPaintEvent* event);
private:
MainMenuListView* menu;
};
public:
MainMenuListView(QWidget* parent = nullptr, const QString& header = QString("Header"));
void headerAreaPaintEvent(QPaintEvent *event);
int headerAreaWidth();
protected:
void resizeEvent(QResizeEvent* event);
private:
QWidget* headerArea;
QString headerText;
};
MainMenuListView::Header::Header(MainMenuListView* parent) : QWidget(parent), menu(parent) {}
QSize MainMenuListView::Header::sizeHint() const
{
return QSize(menu->headerAreaWidth(), fontMetrics().height());
}
void MainMenuListView::Header::paintEvent(QPaintEvent* event)
{
menu->headerAreaPaintEvent(event);
}
MainMenuListView::MainMenuListView(QWidget* parent, const QString& header) : QListView(parent), headerText(header)
{
headerArea = new Header(this);
setViewportMargins(0, fontMetrics().height(), 0, 0);
}
void MainMenuListView::headerAreaPaintEvent(QPaintEvent* event)
{
QPainter painter(headerArea);
painter.fillRect(event->rect(), Qt::lightGray);
painter.setPen(Qt::black);
painter.drawText(0, 0, headerArea->width(), fontMetrics().height(), Qt::AlignCenter, headerText);
}
int MainMenuListView::headerAreaWidth()
{
return width();
}
void MainMenuListView::resizeEvent(QResizeEvent* event)
{
QListView::resizeEvent(event);
headerArea->adjustSize();
}
在Debian Qt5.x.x下测试和工作
结果: