Reputation: 19379
The code creates a single QTableView
assigned to QAbstractTableModel
:
Questions: 1. How to change the header background color to blue? 2. How to change the lower portion of the TableView (currently white) to orange.
import sys, os
from PyQt4 import QtCore, QtGui
app=QtGui.QApplication(sys.argv)
class TableModel(QtCore.QAbstractTableModel):
def __init__(self):
QtCore.QAbstractTableModel.__init__(self)
self.items=['One','Two','Three','Four','Five','Six','Seven']
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.items)
def columnCount(self, index=QtCore.QModelIndex()):
return 1
def data(self, index, role):
if not index.isValid() or not (0<=index.row()<len(self.items)):
return QtCore.QVariant()
item=str(self.items[index.row()])
if role==QtCore.Qt.UserRole:
return item
if role==QtCore.Qt.DisplayRole:
return item
if role==QtCore.Qt.TextColorRole:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.white))
if role == QtCore.Qt.BackgroundRole:
if index.row()%2:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.gray))
else:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.darkGray))
if role == QtCore.Qt.TextAlignmentRole:
return (QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
def headerData(self, column, orientation, role=QtCore.Qt.DisplayRole):
if role == QtCore.Qt.TextAlignmentRole:
return (QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
if role == QtCore.Qt.BackgroundRole:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue))
if role == QtCore.Qt.ForegroundRole:
if orientation == QtCore.Qt.Horizontal:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.red))
elif orientation == QtCore.Qt.Vertical:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
if role == QtCore.Qt.DisplayRole and orientation == QtCore.Qt.Horizontal:
return QtCore.QString('Horizont Column')
if role == QtCore.Qt.DisplayRole and orientation == QtCore.Qt.Vertical:
return QtCore.QString('Vertical Column')
if role == QtCore.Qt.FontRole:
return QtGui.QFont('Times', pointSize=5, weight=-1, italic=True)
class TableView(QtGui.QTableView):
def __init__(self, parent=None):
super(TableView, self).__init__(parent)
self.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
myModel=TableModel()
self.setModel(myModel)
view=TableView()
view.show()
sys.exit(app.exec_())
Upvotes: 2
Views: 3471
Reputation: 18524
Second question:
QTableView
is a QFrame
, you should change color of whole frame, but of course next code:
QFrame
{
background-color:yellow
}
will change background color of many other widgets, so it is not a solution. To apply this property only to your specific tableview just set some object name to it with
tableView->setObjectName("myFrame");
and use:
#myFrame
{
background-color:yellow
}
For header item color use next stylesheet
:
QHeaderView::section
{
background-color:blue
}
So result will be:
As you can see, sections have blue color and other area of QTableView
has yellow color which is separate from color of model data
Upvotes: 3