我正在尝试获取 TableView(来自 qt5.12 中引入的纯 qml 的新视图),其列可以动态调整它们的大小以填充额外的可用空间,但它不起作用
这是我的最小可重现示例:-
main.qml:-
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15
Window {
id: window
width: 640
height: 480
visible: true
title: qsTr("Hello World")
TableView {
anchors.fill: parent
model: KoolModel
// columnWidthProvider: function (_) { return parent.width/3} // Method 1, Does not work
delegate: Frame {
// implicitWidth: parent.width/3 //Method 2, Does not work
implicitWidth: 640/3 // works but not the solution for my problem
Label {
text: display
anchors.centerIn: parent
}
}
}
}
如果我执行此代码,我会得到以下信息:-
这是所需的输出,但是当我调整窗口大小时,列应该扩展,但由于硬编码隐式宽度而不会发生这种情况
如果我使用
columnWidthProvider: function (_) { return parent.width/3}
那么我什么也得不到,只是一个白色的窗口:-
如果我尝试使用这样的绑定
implicitWidth: parent.width/3
我会得到以下信息:-
main.cpp:-
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "models/exams.hpp"
int main(int argc, char* argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Models::Exams exams;
engine.rootContext()->setContextProperty("KoolModel", &exams);
const QUrl url(QStringLiteral("qrc:/main.qml"));
engine.load(url);
return app.exec();
}
模型/考试.cpp
#pragma once
#include <QAbstractTableModel>
#include <QString>
#include <map>
namespace Models {
class Exams : public QAbstractTableModel {
private:
struct DS {
QString title;
unsigned int marks;
int state;
std::vector<int>* questions = nullptr;
};
//id and exams
std::map<int, DS> exams;
public:
Exams();
// QAbstractItemModel interface
int rowCount(const QModelIndex& parent) const override;
int columnCount(const QModelIndex& parent) const override;
QVariant data(const QModelIndex& index, int role) const override;
// QAbstractItemModel interface
public:
QHash<int, QByteArray> roleNames() const override;
};
} //end namespace Models
模型/考试.cpp:-
#include "exams.hpp"
namespace Models {
Exams::Exams()
{
for (int i = 0; i < 200; i++) { //fill garbage data for now
DS exam {
"Exam" + QString::number(i),
0,
(i * 3) / 2,
nullptr
};
exams[i] = exam;
}
exams[2] = {
"Exam" + QString::number(10000000324),
0,
10,
nullptr
};
}
int Exams::rowCount(const QModelIndex& parent) const
{
return exams.size();
}
int Exams::columnCount(const QModelIndex& parent) const
{
return 3;
}
QVariant Exams::data(const QModelIndex& index, int role) const
{
if (role == Qt::DisplayRole) {
if (index.column() == 0)
return exams.at(index.row()).title;
else if (index.column() == 1)
return exams.at(index.row()).marks;
else if (index.column() == 2)
return exams.at(index.row()).state;
}
return QVariant();
}
QHash<int, QByteArray> Exams::roleNames() const
{
return { { Qt::DisplayRole, "display" } };
}
} // end namepsace Models
我正在使用 Archlinux 存储库中的 Qt 5.15
出于性能原因,除非绝对必要,TableView 不会重新计算其行高或列宽。但是当宽度改变时,你可以通过调用
forceLayout()
来强制它。
onWidthChanged: forceLayout()