Changing background color of a row in a QTableView

2,058 views
Skip to first unread message

Ralf Van Bogaert

unread,
Nov 20, 2011, 6:38:27 AM11/20/11
to lqt-bi...@googlegroups.com
Hello,

I'm trying to wrap my head around how to use the data function of a QStandardItemModel/QSqlTableModel

I've got some working examples of editors and such, no problem there, but what I'd like to do is to set the background color of a specific line in a
QTableView.

I can do this;

local Delegate=QStyledItemDelegate.new_local()

TableView:setItemDelegateForRow(CurrentIndex:row(),Delegate)

However I'm not quite sure what to do with the delegate to change the background color, maybe reimplement the data function?

Can you help?

Thanks and regards

Ralf

Michal Kottman

unread,
Nov 27, 2011, 8:54:06 PM11/27/11
to lqt-bi...@googlegroups.com
On 20 November 2011 12:38, Ralf Van Bogaert <poos...@gmail.com> wrote:
> However I'm not quite sure what to do with the delegate to change the
> background color, maybe reimplement the data function?
>
> Can you help?

This is the way to go, however, it did not work correctly (until now).
After a (very) long debugging session this weekend, I think I found a
problem. An example of usage is attached.

To change the background of an item, you have to handle the
BackgroundRole and return a QVariant containing a QBrush, like so
(non-working code, just demonstrating):

function M:data(index, role)
if role == 0 then -- DisplayRole
return QVariant("Hello")
elseif role == 8 then -- BackgroundRole
return QVariant(QBrush(QColor("red")))
end
return QVariant()
end

However, this does not work, because the constructor QVariant(QBrush)
is not defined. You have to use the custom QVariant:setValue(v) to
handle the special QBrush value:

local v = QVariant()
v:setValue(QBrush(...))

This did not work too, because of some intriguing ways in which
lqtL_qvariant_custom is resolved in shared libraries - only the
version for qtcore module was used. Therefore I split the definitions
for qtcore and qtgui, and now I can run the example and get it show
custom backgrounds. You need to fetch the latest source from repo.

I also discovered another problem, but it is a very deep bug regarding
cpptoxml, which does not provide correct information about virtual
functions - it misses that QAbstractTableModel implements the pure
virtual parent() function, simply because it does not contain the
'virtual' keyword in the header. Therefore lqt requires you to
implement it (even though you shouldn't need to).

I hope you find the example a satisfactory solution for your problem.

lqt_styleditem.lua

Ralf Van Bogaert

unread,
Nov 29, 2011, 4:18:35 PM11/29/11
to lqt-bi...@googlegroups.com
Thank you so much Michal! I will give it a try tomorrow.

Regards

Ralf
Reply all
Reply to author
Forward
0 new messages