gpt4 book ai didi

c++ - 使用QModelIndex设置QTreeWidgetItem的背景

转载 作者:行者123 更新时间:2023-12-02 10:34:50 24 4
gpt4 key购买 nike

我有一个带有qTreeWidget的MainWindow。要将元素添加到此小部件,我已经实现了以下功能:

QTreeWidgetItem *MainWindow::prepareIt(QTreeWidgetItem *it, const QString &name, const QString &descr)
{
it->setText(0, name);
it->setText(1, descr);
return it;
}

QTreeWidgetItem *MainWindow::addRoot(const QString &name, const QString &descr)
{
QTreeWidgetItem *it = prepareIt(new QTreeWidgetItem(ui->treeWidget), name, descr);
it->setBackground( 0, QColor{112, 77, 75} );
it->setBackground( 1, QColor{78, 90, 110} );
return it;
}

QTreeWidgetItem *MainWindow::addChild(QTreeWidgetItem *parent, const QString &name, const QString &descr)
{
auto child = new QTreeWidgetItem(parent);

child->setBackground( 0, QColor{102, 67, 65} );
child->setBackground( 1, QColor{68, 80, 99} );

parent->addChild(prepareIt(child, name, descr));
return child;
}


...
addRoot(...);
addChild(parent,...);
...


它按预期工作。现在,我要右键单击以突出显示此qTreeWidget中的某些条目。在MainWindow的C-Tor中,我实现了:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
...
ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->treeWidget, SIGNAL (customContextMenuRequested(const QPoint &)), this, SLOT (rightClick(const QPoint &)));
...
}

插槽是
void MainWindow::rightClick(const QPoint &pt)
{
QModelIndex idx = ui->treeWidget->indexAt(pt);
if (idx.isValid())
{
qDebug() << idx.data().toString();
qDebug() << idx << "index.row()" << idx.row() << " index.column()" << idx.column();
}
}

该插槽按预期方式调用(qDebug可以正常工作),但是如何从QModelIndex idx到相应的QTreeWidgetItem进行突出显示呢?还是有另一种方法来制作高亮/更改元素的颜色?

提前致谢!!

最佳答案

更改单元格的颜色:

一个可能的解决方案是使用setData()方法:

void MainWindow::rightClick(const QPoint &pt)
{
QModelIndex idx = ui->treeWidget->indexAt(pt);
if (idx.isValid())
{
ui->treeWidget->model()->setData(idx, QColor("red"), Qt::BackgroundRole);
}
}

但这只会更改一个单元格,如果要更改颜色,则必须遍历整行:

更改行颜色:

void MainWindow::rightClick(const QPoint &pt)
{
QModelIndex idx = ui->treeWidget->indexAt(pt);
if (idx.isValid())
{
for(int c=0; c < ui->treeWidget->columnCount(); ++c){
QModelIndex ix = idx.sibling(idx.row(), c);
ui->treeWidget->model()->setData(ix, QColor("red"), Qt::BackgroundRole);
}
}
}

要么:
void MainWindow::rightClick(const QPoint &pt)
{
QTreeWidgetItem *it = ui->treeWidget->itemAt(pt);
if (it)
{
for(int c=0; c < ui->treeWidget->columnCount(); ++c){
it->setBackground(c, QColor("red"));
}
}
}

关于c++ - 使用QModelIndex设置QTreeWidgetItem的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60754934/

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