问题描述
我试图了解模型与数据之间的关系是什么.
I'm trying to understand what should the relationships between the Model and the Data be.
对于我目前的情况,我有一个QTcpServer,它保留了活动套接字的列表.
For my current situation i have a QTcpServer which keeps a list of active sockets.
class TftpServer : public QTcpServer
{
Q_OBJECT
public:
TftpServer(QObject *parent = 0)
:QTcpServer(parent) {}
QList<QTcpSocket *> m_activeSockets;
模型应向视图表示的数据为QList<QTcpSocket *> m_activeSockets;
The Data that the Model should represent to the View is QList<QTcpSocket *> m_activeSockets;
我觉得正确的方法是防止不惜一切代价重复数据,因为这可能导致不一致.意味着View始终应代表真实状态的数据.
I feel like the right way to do it is to prevent the duplication of data at any cost for that can lead to inconsistency. Meaning that at all times View should represent the real state Data.
我尝试了一些方法,但都没有成功,因为我有有限的时间可以花时间测试每种方法.
I have tried some approaches, didn't succeeded in any because i have limited time i can spend testing each approach.
方法:
1.
TftpServer::m_activeSockets
私有,模型通过getter和setter访问它.
TftpServer::m_activeSockets
private, Model accesses it through getters and setters.
- 缺陷:如何在模型内的
TftpServer::m_activeSockets
中调用方法?
- Flaw: How to call methods from the
TftpServer::m_activeSockets
within the Model?
2.
TftpServer
的模型朋友类.直接访问TftpServer::m_activeSockets
.
Model friend class of TftpServer
. Directly accesses TftpServer::m_activeSockets
.
- 执行失败.
3.
TftpServer::m_activeSockets
公开.模型具有公共参考
TftpServer::m_activeSockets
public. Model has a public reference
QList<QTcpSocket *> & m_activeSockets;
到TftpServer::m_activeSockets
.
- 缺陷:公开提供敏感数据
我想找出一个最优的解决方案(随便提出建议)被认为是最优的.
并听取他们是否坚持不使用单个数据源的优点(在这种情况下,该模型将仅具有TftpServer::m_activeSockets
的副本作为其参数,并在更改时与之同步).
And hear if their are pros of not insisting on a single Data source (in which case the model would just have a copy of TftpServer::m_activeSockets
as its parameter and sync with it on changes).
推荐答案
您正在滥用Qt的模型视图体系结构-无需传递实际的套接字.您想要的是对连接列表进行建模,因此只需实施即可.连接具有一些参数-这些参数可以映射到模型的列,也可以映射为子行,每个连接都是树中的父项,这取决于更方便的参数.在可视化方面,模型应提供的数据必须有意义.除非您要创建自己的自定义视图或委托,否则QTcpSocket
就是什么都看不到.可以可视化的东西是数字,字符串等.
You're abusing Qt's model-view architecture - there's no need to pass actual sockets around. What you want is to model a list of connections, so just implement that. Connections have some parameters - those can be mapped to a model's columns, or as child rows with each connection being a parent item in a tree, depending on what's more convenient. The data a model should provide must make sense in terms of visualization. A QTcpSocket
is nothing that can be visualized unless you'll be making your own custom views or delegates. Things that can be visualized are numbers, strings, etc.
您想要做的是将QTcpSocket
仅用作具有某些用于返回主机名,端口等的访问器方法的结构.这样浪费时间将不会节省任何时间.
What you're trying to do is to re-use QTcpSocket
as only a structure with some accessor methods used to return the hostname, port and the like. You won't save any time by abusing it that way.
这篇关于Qt模型视图模式,用于将模型与数据连接的设计选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!