Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 [PyQt] coloring the widget table row
#1
hi;
I created a graphical application with Qtdesigner and pyqt5. To finalize it completely, I started the creation some retouches concerning the coloring of some particular lines of the widget table.here is a reduced part of the code the application of my project

creation of the base and table :

    
def create_database_ils35R(self):
        
	#creating the path to the current folder :
	os.chdir('D:\\workspace_python\\Application_ddm')
    #directory creation 'data_base'
	os.makedirs("D:\\workspace-python\\Application ddm\\data_base", exist_ok=True)          
	#values recovered and introduced into the table 
	date_reading = str(time.strftime("%d-%m-%Y"))
	time_reading = str(time.strftime('%H:%M:%S'))    
	mon1_reading = self.lineEdit_mon1_reading.text()
	mon2_reading = self.lineEdit_mon2_reading.text()
	confirmation = self.lineEdit_confirmation.text()
	#creation and connexion to the database "ils35R"
	connexion = sqlite3.connect('data_base/ils35R.db') 
	# Get a cursor object
	curseur = connexion.cursor()
	# Check if table loc35R does not exist and create it
	curseur.execute('''CREATE TABLE IF NOT EXISTS loc35R (date text, time text,mon1 text, mon2 text,declaration text ) ''')
	#inserting data into table "loc35R" :
	curseur.execute('''INSERT INTO loc35R VALUES (?,?,?,?,?) ''',(date_reading,time_reading, mon1_reading, mon2_reading, confirmation))         
	# Commit the change
	connexion.commit()                     
	#fermeture du cursor
	curseur.close()
	#fermeture de la connexion à la bdd
	connexion.close()

display the contents of the data table in a widget table :


def display_contents_table_loc35R(self):

	os.chdir('D:\\workspace-python\\Application_ddm')
	conn = sqlite3.connect ('data_base/ils35R.db')
	curseur=conn.cursor()

	c=curseur.execute("SELECT * FROM loc35R")
              
	liste_loc35R=c.fetchall()
	# set row count
	self.tableWidget_loc35R.setRowCount(len(liste_loc35R))
          
	for nb in range(len(liste_loc35R)):
		for nombre in range(5):
			self.tableWidget_loc35R.setItem(nb,nombre, QTableWidgetItem(liste_loc35R[nb][nombre]))
        
		self.tableWidget_loc35R.resizeRowsToContents()
		self.tableWidget_loc35R.resizeColumnsToContents()        
            
	#closing the cursor
	curseur.close()

	#closing the connection to the bdd
	conn.close()
   
state checkbutton confirmation :

def state checkbutton_for_correction_loc35R(self):
     
if self.checkBox_loc35R.isChecked()==True :	     
	self.lineEdit_confirmation.setText("OK")
            
else:	                      
	self.lineEdit_confirmation.setText("NO")
the insertion of the data in the table and recovery of this information and the display is done successfully on a table wiget pyqt5.

İmage


The problem I encountered and I do not have to find a solution: I want the row of the table containing the confirmation information to be entirely according to the state of the checkbutton: to have green background for each row of the table widget when checkbutton is checked.: (that is to say each row that whose confirmation column contains the OK string

thanks for help
Quote
#2
#!/usr/bin/python3
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class ColoredTable(QtWidgets.QTableWidget):
    def __init__(self, parent):
        super().__init__()
        item = QtWidgets.QTableWidgetItem()
        self.defaultBrush = (item.foreground(), item.background())
        self.itemChanged.connect(self._itemChanged)
        self._setup()

    def _setup(self):
        self.setRowCount(4)
        self.setColumnCount(2)
        txt = ("a", "b", "c", "d")
        for row in range(4):
            for col in range(2):
                item = QtWidgets.QTableWidgetItem()
                item.setText(txt[row])
                if col == 0:
                    item.setCheckState(False)
                self.setItem(row, col, item)

    def _itemChanged(self, item):
        if bool(item.checkState()):
            fg = QtGui.QColor("#004000")
            bg = QtGui.QColor("#C6EFCE")
        else:
            fg, bg = self.defaultBrush

        row = item.row()
        self.itemChanged.disconnect()
        for col in range(self.columnCount()):
            item = self.item(row, col)
            if item:
                item.setForeground(fg)
                item.setBackground(bg)
        self.itemChanged.connect(self._itemChanged)


class Main(QtWidgets.QMainWindow):
    def __init__(self, parent):
        super().__init__()
        self.ui = QtWidgets.QWidget(self)
        self.setCentralWidget(self.ui)
        self.ui.table = ColoredTable(self)
        self.ui.layout = QtWidgets.QVBoxLayout()
        self.ui.layout.addWidget(self.ui.table)
        self.ui.setLayout(self.ui.layout)
        self.show()


if __name__== '__main__':
    app = QtWidgets.QApplication(sys.argv)
    gui = Main(app)
    sys.exit(app.exec_())
Quote
#3
thanks for answer;
Being a beginner with pyqt5, I will explain my problem in a clearer and easier to understand way

in the following figure, the 'confirmation' column contains:
* the string: 'OK',
* the string 'NO',
* an empty string .

İmage

in my case, I wish that only the lines whose column 'confirmation' which contains the string 'OK' have a green background-color
Quote
#4
I thought you wanted a checkbox.. So when do you want the color change to happen? Is it at load time, or when there are changes in the values of the confirmation column?
Quote
#5
Hi; I arrived to do this code


def afficher_contenu_table_loc35L(self):

	script_path_ils35L = os.path.dirname(os.path.realpath(__file__))#récupérer le répertoire courant
	new_path_ils35L=script_path_ils35L + '\\data_base'  #concaténer au path ci-dessus  le path du dossier data_base
	os.makedirs(new_path_ils35L, exist_ok=True)   #creer le dossier data_base au nouveau path

	self.label_cev_loc35L.setText('<h4 style="color:brown; font-weight: bold;">LOC 35L : Liste totale des opérations durant CEV</h4>')      
		
	conn = sqlite3.connect(new_path_ils35L+'\\ils35L.db')
	curseur=conn.cursor()          
	c=curseur.execute("SELECT * FROM loc35L")
                  
	liste_for_table_cev_loc35L=c.fetchall()
	# set row count
	self.tableWidget_cev_loc35L.setRowCount(len(liste_for_table_cev_loc35L))
	#insertion des donnees de la bdd dans la Qtablewidget:
	for nb_lignes in range(len(liste_for_table_cev_loc35L)):
		for nombre_colonnes in range(10):
			self.tableWidget_cev_loc35L.setItem(nb_lignes,nombre_colonnes, QTableWidgetItem(liste_for_table_cev_loc35L[nb_lignes][nombre_colonnes]))
			#mettre la couleur verte pour la ligne contenant la confirmation 'OK'
			if (self.tableWidget_cev_loc35L.item(nb_lignes,nombre_colonnes).text())=='OK' :
				for j in range(nombre_colonnes+1):      
					self.tableWidget_cev_loc35L.item(nb_lignes,j).setBackground(QtGui.QColor(0, 204, 0))
                                        
	self.tableWidget_cev_loc35L.resizeRowsToContents()
	self.tableWidget_cev_loc35L.resizeColumnsToContents()        
              
	#fermeture du cursor
	curseur.close()

	#fermeture de la connexion à la bdd
	conn.close()


see the result at this picture :

İmage

if thers is somme comment or proposals to help me to improve the code above : it would be ecellent for me
thanks
Quote
#6
why not using stylesheet?

self.tableWidget_cev_loc35L.setSelectionBehavior (QAbstractItemView.SelectRows)
self.tableWidget_cev_loc35L.setStyleSheet(stylesheet(self))
stylesheet def:(example)

def stylesheet(self):
        return """
QTableWidget
{
background: #e9e9e9;
selection-color: white;
border: 1px solid lightgrey;
selection-background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #8ae234, stop: 1  #4e9a06);
color: #202020;
outline: 0;
} 
QTableWidget::item::hover{
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #babdb6, stop: 0.5 #d3d7cf, stop: 1 #babdb6);
}
QTableWidget::item::focus
{
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #8ae234, stop: 1  #4e9a06);
border: 0px;
}
"""
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  PyQt Selected row in Table Widget rarevesselt 3 6,123 Dec-07-2018, 07:00 PM
Last Post: rarevesselt

Forum Jump:


Users browsing this thread: 1 Guest(s)