![]() |
[PyQt] [Solved]How to check if row is selected and grab Name from row - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [PyQt] [Solved]How to check if row is selected and grab Name from row (/thread-37411.html) |
[Solved]How to check if row is selected and grab Name from row - Extra - Jun-06-2022 Hello, I'm trying to get the Item Name from the currently selected row. I'm also trying to make an if statement that checks to make sure a row is selected. This is what I'm aiming for: If no row is selected: print("Please select a row") else: print("The Item's ID is: " , SelectedItemID, "And the Item's Name is: " , "SelectedItemName") I'm able to grab the selected row's Id by taking the item.data(): def getCellText(self): if self.InventoryDisplay.selectedIndexes(): item = self.InventoryDisplay.selectedIndexes()[0] row = self.selectedRow() column = self.selectedColumn() if not item == None: name = item.data() self.sbar.showMessage(str(name)) print(name) global SelectedRowID SelectedRowID = item.data())But how do I grab the item's name and see if a row is selected or not? Thanks In advance. Full Code: #!/usr/bin/env python3 import sys from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtSql import QSqlDatabase, QSqlTableModel from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QMainWindow, QLabel, QLineEdit, QTableWidget, QTableWidgetItem, QGridLayout, QVBoxLayout, QSizePolicy, QSpacerItem, QMessageBox,QSpinBox, QComboBox, QTableView,QStyledItemDelegate) from PyQt5.QtCore import Qt, QMetaObject, QCoreApplication from PyQt5.QtGui import QFont import sqlite3 from AddItemScreen import Ui_AddItemMenu from Constants import MainDatabase, Markup class Ui_MainDisplay(QMainWindow): def __init__(self, parent = None): super(Ui_MainDisplay, self).__init__(parent) self.setObjectName("MainDisplay") self.setGeometry(0, 0, 1123, 903) self.setStyleSheet("background-color: rgb(0, 170, 255);") self.centralwidget = QWidget(self) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.verticalLayout = QVBoxLayout() self.verticalLayout.setContentsMargins(-1, 0, -1, 0) self.verticalLayout.setSpacing(6) self.verticalLayout.setObjectName("verticalLayout") self.AddItemButton = QPushButton(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.AddItemButton.setFont(font) self.AddItemButton.setStyleSheet("background-color: rgb(85, 255, 0);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;\n" "\n" "") self.AddItemButton.setObjectName("AddItemButton") self.verticalLayout.addWidget(self.AddItemButton) self.DeleteItemButton = QPushButton(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.DeleteItemButton.setFont(font) self.DeleteItemButton.setStyleSheet("background-color: rgb(255, 65, 68);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;\n" "") self.DeleteItemButton.setObjectName("DeleteItemButton") self.verticalLayout.addWidget(self.DeleteItemButton) self.CheckoutButton = QPushButton(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.CheckoutButton.setFont(font) self.CheckoutButton.setStyleSheet("background-color: rgb(255, 255, 0);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;\n" "") self.CheckoutButton.setObjectName("CheckoutButton") self.verticalLayout.addWidget(self.CheckoutButton) self.ReturnButton = QPushButton(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.ReturnButton.setFont(font) self.ReturnButton.setStyleSheet("background-color: rgb(255, 170, 32);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;\n" "") self.ReturnButton.setObjectName("ReturnButton") self.verticalLayout.addWidget(self.ReturnButton) self.ScanBarcodeButton = QPushButton(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.ScanBarcodeButton.setFont(font) self.ScanBarcodeButton.setStyleSheet("background-color: rgb(211, 211, 211);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;\n" "") self.ScanBarcodeButton.setObjectName("ScanBarcodeButton") self.verticalLayout.addWidget(self.ScanBarcodeButton) self.SettingsButton = QPushButton(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.SettingsButton.setFont(font) self.SettingsButton.setStyleSheet("background-color: rgb(196, 17, 255);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;") self.SettingsButton.setObjectName("SettingsButton") self.verticalLayout.addWidget(self.SettingsButton) self.RefreshButton = QPushButton(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.RefreshButton.setFont(font) self.RefreshButton.setStyleSheet("background-color: rgb(0, 255, 255);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;\n" "\n" "") self.RefreshButton.setObjectName("RefreshButton") self.verticalLayout.addWidget(self.RefreshButton) spacerItem = QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding) self.verticalLayout.addItem(spacerItem) self.LogoutButton = QPushButton(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.LogoutButton.setFont(font) self.LogoutButton.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;\n" "") self.LogoutButton.setObjectName("LogoutButton") self.verticalLayout.addWidget(self.LogoutButton) self.gridLayout.addLayout(self.verticalLayout, 4, 3, 1, 1) self.Header = QLabel(self.centralwidget) font = QFont() font.setPointSize(15) font.setBold(True) font.setWeight(75) self.Header.setFont(font) self.Header.setStyleSheet("background-color: rgb(0, 0, 0);\n" "color: rgb(255, 255, 255);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-radius: 15px;\n" "border-color: black;\n" "padding: 4px;") self.Header.setAlignment(Qt.AlignmentFlag.AlignCenter) self.Header.setObjectName("Header") self.gridLayout.addWidget(self.Header, 0, 1, 1, 3) self.SearchFilter = QComboBox(self.centralwidget) font = QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.SearchFilter.setFont(font) self.SearchFilter.setStyleSheet("background-color: rgb(255, 255, 255);") self.SearchFilter.setObjectName("SearchFilter") self.gridLayout.addWidget(self.SearchFilter, 2, 1, 1, 1) self.SearchBar = QLineEdit(self.centralwidget) self.SearchBar.setStyleSheet("background-color: rgb(255, 255, 255);") self.SearchBar.setObjectName("SearchBar") self.gridLayout.addWidget(self.SearchBar, 2, 2, 1, 1) self.retranslateUi(self) QMetaObject.connectSlotsByName(self) #---------------------------------------------------------------------------------------------------- # Inventory Display #---------------------------------------------------------------------------------------------------- #Connect to Database self.db = QSqlDatabase.addDatabase('QSQLITE') self.db.setDatabaseName('inventory.db') self.model = QSqlTableModel() self.delrow = -1 self.initializeModel() self.sbar = self.statusBar() self.InventoryDisplay = QTableView() self.InventoryDisplay.setStyleSheet("background-color: rgb(255, 255, 255);") self.InventoryDisplay.setModel(self.model) self.InventoryDisplay.clicked.connect(self.findrow) self.InventoryDisplay.selectionModel().selectionChanged.connect(self.getCellText) self.gridLayout.addWidget(self.InventoryDisplay, 4, 1, 1, 2) self.setCentralWidget(self.centralwidget) #Call the function to calculate the SellPrice self.calculate_sellprice() def initializeModel(self): self.model.setTable('items') self.model.setEditStrategy(QSqlTableModel.OnFieldChange) self.model.select() #------------------------------------------ #Search/Filter #------------------------------------------ #Allows the user to search for items self.SearchFilter.clear() for i in range(self.model.columnCount()): self.SearchFilter.addItem(self.model.headerData(i, QtCore.Qt.Horizontal)) self.SearchFilter.setCurrentIndex(1) self.SearchBar.textChanged.connect(self.filter_table) def filter_table(self, text): userQuery = " {} LIKE '%{}%'".format(self.SearchFilter.currentText(), text.lower()) if text else text self.model.setFilter(userQuery) self.model.select() #------------------------------------------ #---------------------------------- # Update Inventory #---------------------------------- def findrow(self, i): self.delrow = i.row() def getCellText(self): if self.InventoryDisplay.selectedIndexes(): item = self.InventoryDisplay.selectedIndexes()[0] row = self.selectedRow() column = self.selectedColumn() if not item == None: name = item.data() self.sbar.showMessage(str(name)) print(name) global SelectedRowID SelectedRowID = item.data() def selectedRow(self): if self.InventoryDisplay.selectionModel().hasSelection(): row = self.InventoryDisplay.selectionModel().selectedIndexes()[0].row() return int(row) def selectedColumn(self): column = self.InventoryDisplay.selectionModel().selectedIndexes()[0].column() return int(column) #---------------------------------- #------------------------------------------------------------------------ #When Price is Updated Automatically Update SellPrice When Refresh is Hit #------------------------------------------------------------------------ def calculate_sellprice(self): for row in range(self.InventoryDisplay.model().rowCount() - 1): sell_price = str(self.InventoryDisplay.model().index(row, 3).data()) if sell_price: sell_price = f'{float(sell_price.replace(",", ".")) * Markup:.2f}' self.InventoryDisplay.model().setData(self.InventoryDisplay.model().index(row, 4), sell_price) #---------------------------------- #Make Specific Columns Un-Editable/ReadOnly #---------------------------------- class ReadOnlyDelegate(QStyledItemDelegate): def createEditor(self, parent, option, index): print('This column is Read-Only') return delegate = ReadOnlyDelegate(self) self.InventoryDisplay.setItemDelegateForColumn(0, delegate) #ID self.InventoryDisplay.setItemDelegateForColumn(2, delegate) #Quantity self.InventoryDisplay.setItemDelegateForColumn(4, delegate) #SellPrice self.InventoryDisplay.setItemDelegateForColumn(10, delegate) #Date Added #---------------------------------- #---------------------------------------------------------------------------------------------------- def retranslateUi(self, MainDisplay): _translate = QCoreApplication.translate self.setWindowTitle(_translate("MainDisplay", "AdminMenu")) self.AddItemButton.setText(_translate("MainDisplay", "Add Item")) self.DeleteItemButton.setText(_translate("MainDisplay", "Delete Item")) self.CheckoutButton.setText(_translate("MainDisplay", "Check Out")) self.ReturnButton.setText(_translate("MainDisplay", "Return")) self.ScanBarcodeButton.setText(_translate("MainDisplay", "Scan Barcode")) self.SettingsButton.setText(_translate("MainDisplay", "Settings")) self.RefreshButton.setText(_translate("MainDisplay", "Refresh")) self.LogoutButton.setText(_translate("MainDisplay", "Log Out")) self.Header.setText(_translate("MainDisplay", "Admin Menu")) #---------------------------------------------------------------------------------------------------- # Button Actions #---------------------------------------------------------------------------------------------------- #------------------------------------------ #Logout Button #------------------------------------------ #When the Logout button is clicked -> LogoutClicked Function LogoutButton = self.LogoutButton LogoutButton.clicked.connect(self.LogoutClicked) #------------------------------------------ #------------------------------------------ #Add Item Button #------------------------------------------ #When the AddItem button is clicked -> AddItem Function AddItemButton = self.AddItemButton AddItemButton.clicked.connect(self.AddItemClicked) #------------------------------------------ #------------------------------------------ #Remove Item Button #------------------------------------------ #When the RemoveItem button is clicked -> RemoveItem Function RemoveItemButton = self.DeleteItemButton RemoveItemButton.clicked.connect(self.RemoveItemClicked) #------------------------------------------ #------------------------------------------ #Checkout Item Button #------------------------------------------ #When the Checkout button is clicked -> Checkout Function CheckoutButton = self.CheckoutButton CheckoutButton.clicked.connect(self.CheckoutClicked) #------------------------------------------ #------------------------------------------ #Return Item Button #------------------------------------------ #When the Return button is clicked -> Return Function ReturnButton = self.ReturnButton ReturnButton.clicked.connect(self.ReturnClicked) #------------------------------------------ #------------------------------------------ #Scan Barcode Button #------------------------------------------ #When the Scan Barcode button is clicked -> ScanBarcode Function ScanBarcodeButton = self.ScanBarcodeButton ScanBarcodeButton.clicked.connect(self.ScanBarcodeClicked) #------------------------------------------ #------------------------------------------ #Settings Button #------------------------------------------ #When the Settings button is clicked -> Settings Function SettingsButton = self.SettingsButton SettingsButton.clicked.connect(self.SettingsClicked) #------------------------------------------ #------------------------------------------ #Refresh Button #------------------------------------------ #When the More Info button is clicked -> MoreInfo Function RefreshButton = self.RefreshButton RefreshButton.clicked.connect(self.RefreshClicked) #------------------------------------------ #---------------------------------- #Logout Function def LogoutClicked(self): #Print in terminal for testing: print("The Logout Button was clicked") #Switch from this screen to the LoginScreen #(Import LoginScreen here to prevent circular import error) from LoginScreen import Ui_Loginscreen self.win = Ui_Loginscreen() #Define LoginScreen self.win.show() #Show Login Screen self.close() #Close this screen (AdminMenu) #---------------------------------- #---------------------------------- #AddItem Function def AddItemClicked(self): #Print in terminal for testing: print("The Add Item Button was clicked") #Switch from this screen to the AddItems Screen (Scene Swap): self.win = Ui_AddItemMenu() self.win.show() self.close() #---------------------------------- #---------------------------------- #RemoveItem Function def RemoveItemClicked(self): #Print in terminal for testing: print("The Delete Item Button was clicked") self.DeleteConfirmation() #---------------------------------- # Delete Item Confirmation #---------------------------------- def DeleteConfirmation(self): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Warning) msgBox.setText("Are you sure you want to delete this item?") msgBox.setInformativeText("*This cannot be undone") msgBox.setWindowTitle("Delete Item Confirmation") msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No) returnValue = msgBox.exec() if returnValue == QMessageBox.Yes: row = self.InventoryDisplay.currentIndex().row() self.model.removeRow(row) self.initializeModel() self.InventoryDisplay.selectRow(row) #---------------------------------- #---------------------------------- #Checkout Function def CheckoutClicked(self): #Print in terminal for testing: print("The Checkout Button was clicked") #Switch from this screen to the Checkout Popup Screen (Scene Swap): # from CheckoutPopup import Ui_CheckoutPopup # x = Ui_CheckoutPopup() # x.ConfirmClicked() # print("Test: " ,x.CheckoutSpinBox.value()) # self.win = Ui_CheckoutPopup() # self.win.show() # #self.close() self.ex = Ui_CheckoutPopup(parent=self) self.ex.show() #---------------------------------- #---------------------------------- #Return Function def ReturnClicked(self): #Print in terminal for testing: print("The Return Button was clicked") #---------------------------------- #---------------------------------- #ScanBarcode Function def ScanBarcodeClicked(self): #Print in terminal for testing: print("The Scan Barcode Button was clicked") #---------------------------------- #---------------------------------- #Settings Function def SettingsClicked(self): #Print in terminal for testing: print("The Settings Button was clicked") #---------------------------------- #---------------------------------- #Refresh Function def RefreshClicked(self): #Print in terminal for testing: print("The Refresh Button was clicked") #Close and reopen the app (Refresh) self.win = Ui_MainDisplay() self.win.show() self.close() #---------------------------------- #---------------------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------------- # if __name__ == '__main__': # app = QApplication(sys.argv) # win = Ui_MainDisplay() # win.show() # sys.exit(app.exec_()) #---------------------------------------------------------------------------------------------------- # Checkout Popup #---------------------------------------------------------------------------------------------------- class Ui_CheckoutPopup(QtWidgets.QMainWindow): def __init__(self, parent = None): super(Ui_CheckoutPopup, self).__init__(parent) self.setObjectName("Checkout") self.setFixedSize(428, 188) self.setStyleSheet("background-color: rgb(0, 170, 255);") self.centralwidget = QtWidgets.QWidget() self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.messageText = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setPointSize(15) font.setBold(True) font.setWeight(75) self.messageText.setFont(font) self.messageText.setAlignment(QtCore.Qt.AlignCenter) self.messageText.setObjectName("messageText") self.verticalLayout.addWidget(self.messageText) self.CheckoutSpinBox = QtWidgets.QSpinBox(self.centralwidget) self.CheckoutSpinBox.setStyleSheet("background-color: rgb(255, 255, 255);") self.CheckoutSpinBox.setObjectName("CheckoutSpinBox") self.verticalLayout.addWidget(self.CheckoutSpinBox) self.ConfirmButton = QtWidgets.QPushButton(self.centralwidget) font = QtGui.QFont() font.setPointSize(12) font.setBold(True) font.setWeight(75) self.ConfirmButton.setFont(font) self.ConfirmButton.setStyleSheet("background-color: rgb(225, 225, 225);\n" "border-style: outset;\n" "border-width: 2px;\n" "border-color: black;\n" "padding: 4px;") self.ConfirmButton.setObjectName("ConfirmButton") self.verticalLayout.addWidget(self.ConfirmButton) self.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar() self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.retranslateUi(self) QtCore.QMetaObject.connectSlotsByName(self) #-------------------------------------------------- self.CheckoutSpinBox.valueChanged.connect(self.currentValue) #------------------------------------------ #Confim Button #------------------------------------------ #When the Confirm button is clicked -> Confirm Function ConfirmButton = self.ConfirmButton ConfirmButton.clicked.connect(self.ConfirmClicked) #------------------------------------------ #------------------------------------------ def currentValue(self): #This stores the selected Item's Name SelectedItemName = "" #Show the current value of the SpinBox in real time self.messageText.setText("You are taking: "+str(self.CheckoutSpinBox.value()) + " " + SelectedItemName) def ConfirmClicked(self): CheckoutQuantity = self.CheckoutSpinBox.value() print("Quantity you are taking: ", CheckoutQuantity) #Get the SelectedRow ID from the global variable SelectedRowID in getCellText() print("The Selected Item's ID is: ", SelectedRowID) #Connect to the inventory database (inventory.db) connection = sqlite3.connect(MainDatabase) cursor = connection.cursor() #Update the quantity cursor.execute("UPDATE items SET Quantity = Quantity - ? WHERE ID = ?",(CheckoutQuantity, SelectedRowID,)) connection.commit() #Close the connection connection.close() #Close the window self.parent() self.close() # #Switch from this screen to the AdminMenu # #(Import AdminMenu here to prevent circular import error) # from AdminMenu import Ui_MainDisplay # self.win = Ui_MainDisplay() #Define the AdminMenu # self.win.show() #Show the AdminMenu # self.close() #Close this screen #-------------------------------------------------- def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.messageText.setText(_translate("MainWindow", "How much quantity are you taking:")) self.ConfirmButton.setText(_translate("MainWindow", "Confirm")) def main(): app = QApplication(sys.argv) win = Ui_MainDisplay() win.show() sys.exit(app.exec_()) if __name__ == "__main__": main() RE: How to check if row is selected and grab Name from row - Axel_Erfurt - Jun-06-2022 The table is sized down by the number of rows. If you click on an empty space below it is no longer the table. The function is therefore only effective if a line within the table is clicked. If you want the name use column 1 def getCellText(self): if self.InventoryDisplay.selectedIndexes(): model= self.InventoryDisplay.model() row = self.selectedRow() column = 1 name = model.data(model.index(row, column)) self.sbar.showMessage(str(name)) print(name) RE: How to check if row is selected and grab Name from row - Extra - Jun-06-2022 Thanks, that helped a lot. Now is there a way to tell if a full row is selected (As shown in the attachment) that way I can use it in an if statement checking if a full row is selected or not? RE: How to check if row is selected and grab Name from row - Axel_Erfurt - Jun-07-2022 If you want to select a whole row, use SelectionBehavior self.InventoryDisplay = QTableView() self.InventoryDisplay.setSelectionBehavior(1)0 Selecting single items. 1 Selecting only rows. 2 Selecting only columns. RE: How to check if row is selected and grab Name from row - Extra - Jun-07-2022 (Jun-07-2022, 07:53 AM)Axel_Erfurt Wrote: If you want to select a whole row, use SelectionBehavior Thanks for this. It's helpful and very useful in my program, but I'm looking to have the program make sure a row is currently selected before a popup window opens. So if nothing is selected and the user presses a button, a msgBox pops up reminding the user to select a row before clicking the button. Once the user clicks on a row (the row is currently highlighted) then a different popup window opens. This is to prevent a crash when the program first opens. Because nothing is selected, If the user hits the checkout button the program will crash because no item is currently selected. So I need to either check to make sure a row is selected or when the program first opens the first row is selected by default. Any suggestions on how to do that? Thanks. RE: How to check if row is selected and grab Name from row - Axel_Erfurt - Jun-08-2022 (Jun-07-2022, 11:46 PM)Extra Wrote: So if nothing is selected and the user presses a button, a msgBox pops up reminding the user to select a row before clicking the button. That is possible, for example the checkout button def CheckoutClicked(self): #Print in terminal for testing: if self.InventoryDisplay.selectedIndexes(): print("row selected") #Switch from this screen to the Checkout Popup Screen (Scene Swap): # from CheckoutPopup import Ui_CheckoutPopup # x = Ui_CheckoutPopup() # x.ConfirmClicked() # print("Test: " ,x.CheckoutSpinBox.value()) # self.win = Ui_CheckoutPopup() # self.win.show() # #self.close() self.ex = Ui_CheckoutPopup(parent=self) self.ex.show() else: msgBox = QMessageBox.warning(None, "Error", "No row is selected!\nPlease select a row", QMessageBox.Close) RE: How to check if row is selected and grab Name from row - Extra - Jun-08-2022 Thanks! That's exactly what I was looking for. |