如何将带有数据的标题添加到 Qt 中的 QTableWidget?
我仍在学习 Qt,我感谢 SO 社区为我的 Qt 问题提供了很好、非常及时的答案。谢谢。
我对向 QTableWidget 添加标头的想法感到非常困惑。我想做的是有一个包含有关团队成员信息的表。成员的每一行
都应包含他的名字和姓氏,每个名字都在自己的单元格中,一个单元格中包含电子邮件地址,另一个单元格中包含办公室。我希望在这些列上方有一个 header
来对它们进行适当的命名。
我试图从简单的开始,只让标题显示“姓氏”(如姓氏)。这是我的代码。
int column = m_ui->teamTableWidget->columnCount();
m_ui->teamTableWidget->setColumnCount(column+1);
QString* qq = new QString("Last");
m_ui->teamTableWidget->horizontalHeader()->model()->setHeaderData(0,
Qt::Horizontal, QVariant(QVariant::String, &qq));
我的表格被正确渲染,但标题不包含我所期望的内容。它包含 1 个包含文本“1”的单元格。
显然我在这里做了一些非常愚蠢的事情,这是错误的,但我迷路了。我不断地翻阅文档,却一无所获。
感谢您的任何和所有帮助。
I'm still learning Qt and I am indebted to the SO community for providing me with great, very timely answers to my Qt questions. Thank you.
I'm quite confused on the idea of adding a header to a QTableWidget
. What I'd like to do is have a table that contains information about team members. Each row
for a member should contain his first and last name, each in its own cell, an email address in one cell, and office in the other cell. I'd to have a header
above these columns to name them as appropriate.
I'm trying to start off easy and get just the header to display "Last" (as in last name). Here is my code.
int column = m_ui->teamTableWidget->columnCount();
m_ui->teamTableWidget->setColumnCount(column+1);
QString* qq = new QString("Last");
m_ui->teamTableWidget->horizontalHeader()->model()->setHeaderData(0,
Qt::Horizontal, QVariant(QVariant::String, &qq));
My table gets rendered corretly, but the header doesn't contain what I would expect. It contains 1 cell that contains the text "1".
I am obviously doing something very silly here that is wrong, but i am lost. I keep pouring over the documentation, finding nothing.
Thanks for any and all help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的解决方案是
setHorizontalHeaderLabels(myListOfHeaderLabels)
。The easiest solution is
setHorizontalHeaderLabels(myListOfHeaderLabels)
.我看到了一个潜在的问题,以及一种更简单的方法来做到这一点。
首先,问题是:
我想你想这样做:
现在,为标题项设置数据的更简单方法:
I see one potential problem, and also an easier way to do this.
First, the problem:
I think you want to do this instead:
Now, the easier way to set the data for a header item:
应引导我走向正确位置的人的要求,我将我完成此操作的方式发布为答案,并且我接受它。
At the request of the person who steered me toward the right place, I am posting the way I accomplished this as an answer and I am accepting it.
对于后代:
QAbstractItemModel 中 setHeaderData() 和 headerData() 的默认实现不执行任何操作。您可以(应该?)(重新)实现 headerData() 以返回有用的标签。
For posterity:
The default implimentations of setHeaderData() and headerData() in QAbstractItemModel do not do anything. You can (should?) (re)impliment headerData() in order to return useful a label.