gpt4 book ai didi

c++ - QtableWidget header 中的复选框

转载 作者:太空狗 更新时间:2023-10-29 23:13:00 25 4
gpt4 key购买 nike

如何在 QTableWidget Header 上设置复选框。如何在 QHeaderView 中添加全选复选框它不显示复选框..

 QTableWidget* table = new QTableWidget();
QTableWidgetItem *pItem = new QTableWidgetItem("All");
pItem->setCheckState(Qt::Unchecked);
table->setHorizontalHeaderItem(0, pItem);

最佳答案

Here, at Qt Wiki,它说它没有捷径,你必须自己继承 headerView。

以下是该 wiki 答案的摘要:

“目前没有用于在标题中插入小部件的 API,但您可以自己绘制复选框以将其插入标题中。

您可以做的是子类化 QHeaderView,重新实现 paintSection()然后调用drawPrimitive()在您希望拥有此复选框的部分中使用 PE_IndicatorCheckBox。

您还需要重新实现 mousePressEvent()检测复选框何时被单击,以便绘制选中和未选中状态。

下面的例子说明了如何做到这一点:

#include <QtGui>

class MyHeader : public QHeaderView
{
public:
MyHeader(Qt::Orientation orientation, QWidget * parent = 0) : QHeaderView(orientation, parent)
{}

protected:
void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
painter->save();
QHeaderView::paintSection(painter, rect, logicalIndex);
painter->restore();
if (logicalIndex == 0)
{
QStyleOptionButton option;
option.rect = QRect(10,10,10,10);
if (isOn)
option.state = QStyle::State_On;
else
option.state = QStyle::State_Off;
this->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter);
}

}
void mousePressEvent(QMouseEvent *event)
{
if (isOn)
isOn = false;
else
isOn = true;
this->update();
QHeaderView::mousePressEvent(event);
}
private:
bool isOn;
};


int main(int argc, char **argv)
{
QApplication app(argc, argv);
QTableWidget table;
table.setRowCount(4);
table.setColumnCount(3);

MyHeader *myHeader = new MyHeader(Qt::Horizontal, &table);
table.setHorizontalHeader(myHeader);
table.show();
return app.exec();
}

关于c++ - QtableWidget header 中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42464590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com