[英]C++ Constant parameter of a class
I'm implementing custom TableModel ( MyTableModel
class) in Qt, based on QAbstractTableModel
to display the data stored in an object of MyDataStorage
class. 我基于
QAbstractTableModel
在Qt中实现自定义TableModel( MyTableModel
类),以显示存储在MyDataStorage
类的对象中的数据。 It requires defining rowCount()
and columnCount()
functions for MyTableModel
. 它需要为
MyTableModel
定义rowCount()
和columnCount()
函数。
In my case I have a class MyDataStorage
that contains a QList<MyData> dataList
. 就我而言,我有一个
MyDataStorage
类,其中包含QList<MyData> dataList
。 MyData
class consists of a five member variables (one int
, one QDate
and three QString
s). MyData
类包含五个成员变量(一个int
,一个QDate
和三个QString
)。 MyTableModel::rowCount()
returns simply the length of MyDataStorage
's dataList
. MyTableModel::rowCount()
仅返回MyDataStorage
的dataList
的长度。 MyTableModel::columnCount()
must return the number of members of MyData
that are to be shown in the table, so first I defined the public method MyData::getParameterCount() {return 5;}
, so that I could use it as shown below: MyTableModel::columnCount()
必须返回要在表中显示的MyData
成员的数量,因此首先我定义了公共方法MyData::getParameterCount() {return 5;}
,以便可以如图所示使用它下面:
class MyTableModel : public QAbstractTableModel
{
Q_OBJECT
MyDataStorage& im;
public:
explicit InfoTableModel(MyDataStorage& m, QObject *parent = 0);
int rowCount();
inline int columnCount() {return m.getLast().getParameterCount()};
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
//...
}
I feel it is not the best solution as the list can be empty. 我觉得这不是最好的解决方案,因为列表可以为空。 Other possibilites are to define:
其他可能的定义如下:
MyDataStorage
, MyDataStorage
等效功能, MyData
, MyData
静态成员, inline int columnCount() {return 5;}
as MyTableModel
has to be changed with every change of the underlying data model (it's the most obvious solution, but I'm scared if this is correct) inline int columnCount() {return 5;}
因为MyTableModel
基础数据模型的每次更改都必须更改MyTableModel
(这是最明显的解决方案,但是我怕这是正确的) but I don't feel any of them is the proper solution, as the number of MyData
members will change in the future. 但我认为其中任何一个都不是正确的解决方案,因为
MyData
成员的数量将来会改变。
What are your propositions? 你有什么主张?
If you do not have an element in your storage, then your row count is zero, as is your column count. 如果存储中没有元素,则行数和列数均为零。 Therefore you should just check this:
因此,您应该检查一下:
inline int columnCount() { return (m.isEmpty() ? 0 : m.getLast().getParameterCount()) };
You can declare MyData::getParameterCount()
as static
member and then refer to it like this: 您可以将
MyData::getParameterCount()
声明为static
成员,然后像这样引用它:
inline int columnCount() const {return MyData::getParameterCount();}
In that case you don't need any MyData
objects. 在这种情况下,您不需要任何
MyData
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.