C++ ListStringModel中行的Qt背景色
我尝试用这段代码设置行的颜色,但它不起作用C++ ListStringModel中行的Qt背景色,c++,qt,C++,Qt,我尝试用这段代码设置行的颜色,但它不起作用 QColor dataColor =Qt::red; row = seznamChyb->rowCount(); seznamChyb->insertRows(row,1); QModelIndex index = seznamChyb->index(row); ui->listView->setCurrentIndex(index); seznamChyb->se
QColor dataColor =Qt::red;
row = seznamChyb->rowCount();
seznamChyb->insertRows(row,1);
QModelIndex index = seznamChyb->index(row);
ui->listView->setCurrentIndex(index);
seznamChyb->setData(index,dataColor, Qt::BackgroundRole);
seznamChyb->setData(index,data);
我不确定什么类型的
seznamChyb
和ListStringModel
。但是更改行的背景颜色需要实现方法qabstractemmodel::data()
我为这个问题写了一个例子,它确实很有效:
#include <QApplication>
#include <QTableView>
#include <QAbstractListModel>
class StringListModel : public QAbstractListModel
{
public:
StringListModel(const QStringList &strings, QObject *parent = 0)
: QAbstractListModel(parent), stringList(strings) {}
int rowCount(const QModelIndex &) const
{
return stringList.count();
}
QVariant data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole)
return stringList.at(index.row());
if (role == Qt::BackgroundColorRole && index.row() == 0) // Look this.
return QBrush(Qt::red);
else
return QVariant();
}
private:
QStringList stringList;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView tableView;
QStringList list;
list << "a" << "b" << "c";
StringListModel model(list);
tableView.setModel(&model);
tableView.show();
return a.exec();
}
#包括
#包括
#包括
类StringListModel:公共QabStrictListModel
{
公众:
StringListModel(常量QStringList和字符串,QObject*parent=0)
:QAbstractListModel(父),stringList(strings){}
int行计数(常量QModelIndex&)常量
{
返回stringList.count();
}
QVariant数据(常量QModelIndex和索引,int角色)常量
{
如果(角色==Qt::DisplayRole)
返回stringList.at(index.row());
if(role==Qt::BackgroundColorRole&&index.row()==0)//看这个。
返回QBrush(Qt::红色);
其他的
返回QVariant();
}
私人:
QStringList字符串列表;
};
int main(int argc,char*argv[])
{
质量保证申请a(argc、argv);
QTableView表视图;
QStringList表;
列表seznamChyb->insertRows(行,1);
=>seznamChyb->insertRows(行,0);
或seznamChyb->index(行);
=>seznamChyb->index(行,1)
如果我将0更改为1或添加1,则它不会写入文本并将其回注为白色,不知道发生了什么。请查看我的示例代码。然后再次检查您的代码。thx但是我使用这个预定义的ListStringModel类,我不重新实现任何函数,我现在也不知道如何重新实现它。