|
3Qter豆
本帖最后由 inanity 于 2017-12-18 22:34 编辑
主要想实现的功能是:界面中用gridview画视图,gridview的model数据是由QQmlContext::setcontextproperty加载的QList<QOBJECT*>。但修改QList<QOBJECT*>中元素后,用setcontextproperty重置模型时,程序会崩溃。
有几个问题:
1.程序是用setcontextproperty重置模型后几次才崩溃的,也就是能运行N次setcontextproperty,界面也能显示出QList中的数据。
2.每次setcontextproperty后,程序内存会涨2-3M左右,而且内存值不会往下掉(也就是说setcontextproperty会申请一些空间,还不会释放)。
3.qt creator的debug模式是不是有内存限制,内存涨到500M左右有些要用内存操作就会保存,比如加载图片用的QImage。4.是否用继承QAbstractListModel比使用QList来加载Model数据好些。
以下是简化过的部分代码:
main.qml- GridView{
- id:gridview
- ...
- model: templist
- delegate: gridview_component
- }
- }
- Component{
- id:gridview_component
- Item{
- ...
- Rectangle{
- ...
- Text {
- id: text11
- ...
- text: text1
- }
- Text {
- id: text22
- ...
- text: text2
- }
- Text {
- id: text33
- ...
- text: text3
- }
- }
- }
复制代码 main.cpp:
temp是QList<QObect*>
- int main(int argc, char *argv[])
- {
- QGuiApplication app(argc, argv);
- QQmlApplicationEngine engine;
- QQmlContext* context=engine.rootContext();
- Midware *midware= new Midware();
- midware->setContext(context);
- context->setContextProperty("templist",QVariant::fromValue(midware->temp));
- engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
- return app.exec();
- }
复制代码
Midware类包含一个QTcpsocket,其中
- connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(readMsg()));
复制代码 readMsg中...是省略的接收消息的代码,消息不完整不会进入下面代码,会直接return 出去。
temp是QList<QObect*>- void Midware::readMsg()
- {
- while(true)
- {
- ...
- qDeleteAll(temp);
- temp.clear();
- qsrand(time(0));
- int max=qrand()%16+1;
- for(int i=0;i<max;i++)
- {
- Data* dataTemp=new Data();
- temp.append(dataTemp);
- }
- context->setContextProperty("templist" ,nullptr);
- context->setContextProperty("templist" , QVariant::fromValue(temp));
- }
- }
复制代码 加这句有时能跑的时间长点,不知道是不是那几次内存没涨到限制值。
- context->setContextProperty("templist" ,nullptr);
复制代码
Data类:
- class Data :public QObject
- {
- Q_OBJECT
- Q_PROPERTY(QString text1 READ read_text1 CONSTANT)
- Q_PROPERTY(QString text2 READ read_text2 CONSTANT)
- Q_PROPERTY(QString text3 READ read_text3 CONSTANT)
- private:
- QString text1;
- QString text2;
- QString text3;
- public:
- Data(){ text1="text1"; text2="text2"; text3="text3";}
- ~Data();
- QString read_text1() const { return this->text1; }
- QString read_text2() const { return this->text2; }
- QString read_text3() const { return this->text3; }
- };
复制代码
|
|