如何使 restoreState() 和 saveState() 在 QTableView 类中正常工作? [英] HowTo make restoreState() and saveState() work correctlly to QTableView class?

查看:76
本文介绍了如何使 restoreState() 和 saveState() 在 QTableView 类中正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想说,我的问题已经在这里讨论过,关于 SO,以及 这里是.但答案并不好...

First of all, I wanted to say, that my problem was already discuss here, on SO, and here it is. But the answers are not the good ones...

所以,这是问题:我有一个 QTableView 类,带有一个简单的 model,与 tableView-> 连接;setModel(model); 方法.例如,我有 4-5 列.我启动了我的项目应用程序,并对列宽进行了一些更改.按退出后,我的项目应用程序将 tableView->horizo​​ntalHeader()->saveState(); 数据的状态与 QSettings 保存到文件中.当我再次启动我的应用程序时,它会变成这样:

So, here is the problem: I have a QTableView class, with a simple model, connected with tableView->setModel(model); method. For example, I have 4-5 columns. I started up my project application and made some changes with columns width. After I pressed Exit, my project app save state of the tableView->horizontalHeader()->saveState(); data with QSettings to file. And when I starts up my app again, it makes something like this:

tableView->horizontalHeader()->restoreState(/* data from settings ini file */);

但是,什么也没发生!列宽具有标准宽度.它们不会随我存储的值而改变!:(

But, nothing happens! The columns widths has standard width. They are not changed with my stored values! :(

谢谢!

PS:这个问题在 QTreeView 类中不会变得明显.使用 QTreeView 一切正常!

PS: This problem not become apparent with QTreeView class. With QTreeView all is ok!

推荐答案

我试图重现您的问题,但对我来说一切正常.这是我所做的:

I tried to reproduce your problem, but everything is working fine for me. Here is what I did :

使用 Qt-Designer,我在表单上放置了一个 QTableView(名为 tbvTest).

With Qt-Designer, I put a QTableView (named tbvTest) on my form.

在我的表单的构造函数中,这是我写的:

In the constructor of my form, here is what I've written :

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->tbvTest->setModel(new TableModel);

    QSettings MySetting(QSettings::IniFormat, QSettings::UserScope, "Test");
    QByteArray MyArray = MySetting.value("column_width", "").toByteArray();
    ui->tbvTest->horizontalHeader()->restoreState(MyArray);
}

(请注意,在我的 main.cpp 中,我设置了 ApplicationNameOrganizationNameOrganizationDomain)

(note that in my main.cpp, I set the ApplicationName, OrganizationName and OrganizationDomain)

在我的表单的析构函数中,这是我写的:

In the destructor of my form, here is what I've written :

Widget::~Widget()
{
    QByteArray MyArray = ui->tbvTest->horizontalHeader()->saveState();
    QSettings MySetting(QSettings::IniFormat, QSettings::UserScope, "Test");
    MySetting.setValue("column_width", MyArray);

    delete ui;
}

如果我运行应用程序并更改列宽,退出应用程序并再次运行它,列宽会正确恢复.

If I run the application and change the column width, quit the app and run it again, the column widths are correctly restored.

有什么我做的和你不同的吗?

Is there something I'm doing different from you ?

这篇关于如何使 restoreState() 和 saveState() 在 QTableView 类中正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆