Python Forum
[PyQt] [Solved]Add a SpinBox to MsgBox or Carry Variable Over?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] [Solved]Add a SpinBox to MsgBox or Carry Variable Over?
#1
Hello,

I'm trying to build my Checkout function which when an Item/row is selected and the 'Checkout' button is clicked a spinBox pops up asking the user how much quantity they are taking. The user enters the quantity they are taking into the spinbox and that value is stored once they hit the submit button, located right below the spinbox. That value is then used to subtract it from the current quantity.

Right now I have a separate python script for my spin box called Test2.py:
import sys
from PyQt5.QtWidgets import (QApplication, QPushButton, QWidget, QLabel, QVBoxLayout,QSpinBox)
from PyQt5.QtCore import Qt

class spindemo(QWidget):
   def __init__(self, parent = None):
      super(spindemo, self).__init__(parent)
      
      layout = QVBoxLayout()
      self.messageText = QLabel("How much quantity are you taking?")
      self.messageText.setAlignment(Qt.AlignCenter)
      layout.addWidget(self.messageText)
      self.CheckoutSpinBox = QSpinBox()

      self.ConfirmButton = QPushButton()
      self.ConfirmButton.setText("Confirm")

		
      layout.addWidget(self.CheckoutSpinBox)
      layout.addWidget(self.ConfirmButton)

      self.CheckoutSpinBox.valueChanged.connect(self.currentValue)
      self.setLayout(layout)
      self.setWindowTitle("Checkout")

      #------------------------------------------
                        #Confim Button
      #------------------------------------------
      #When the Confirm button is clicked -> Confirm Function
      ConfirmButton = self.ConfirmButton
      ConfirmButton.clicked.connect(self.ConfirmClicked)
      #------------------------------------------
		
   def currentValue(self):
      #Show the current value of the SpinBox in real time
      self.messageText.setText("You are taking: "+str(self.CheckoutSpinBox.value()))

   def ConfirmClicked(self):
      CheckoutQuantity = self.CheckoutSpinBox.value()
      print("Quantity you are taking: ", CheckoutQuantity)
      return CheckoutQuantity


def main():
   app = QApplication(sys.argv)
   ex = spindemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()


The Test2.py is called by my checkout function in the Main.py
#----------------------------------
    #Checkout Function
    def CheckoutClicked(self):
        #Print in terminal for testing:
        print("The Checkout Button was clicked")
        #Switch from this screen to the AddItems Screen (Scene Swap):
        self.win = spindemo()
        self.win.show()
        #self.close()
#----------------------------------
I tried making the CheckoutQuantity variable global and imported it into my Main.py, but it did not work.

So I'm wondering if I can make a msgbox contain a SpinBox that way I can keep everything in my Main.py
OR
Is there a way I can carry over the CheckoutQuantity variable from Test2.py and use it my Main.py without getting any errors?

Thanks in advance.
Reply
#2
Just an idea

import sys
from PyQt5.QtWidgets import (QApplication, QPushButton, QWidget, QLabel, QVBoxLayout,QSpinBox, QMainWindow)
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    def __init__(self, parent = None):
      super(MainWindow, self).__init__(parent)
      
      self.ex = None
      self.checkout_value = 0
      cw = QWidget()
      vbox = QVBoxLayout()
      self.btn = QPushButton("Click", clicked = self.btn_clicked)
      self.lbl = QLabel(alignment = Qt.AlignCenter)
      vbox.addWidget(self.btn)
      vbox.addWidget(self.lbl)
      cw.setLayout(vbox)
      self.setCentralWidget(cw)
      self.setGeometry(100, 100, 400, 400)
      
      
    def btn_clicked(self):
        if not self.ex:
            self.ex = spindemo(parent = self)
            self.ex.show()
            
    def update_label(self):
        self.lbl.setText(f'CheckoutQuantity: {self.checkout_value}')
        print((f'CheckoutQuantity: {self.checkout_value}'))
        self.ex = None
        
        
    
class spindemo(QWidget):
   def __init__(self, parent = None):
      super(spindemo, self).__init__(parent)
       
      self.setStyleSheet("QSpinBox, QPushButton {background: #3465a4; color: #eeeeec;}")
      layout = QVBoxLayout()
      self.messageText = QLabel("How much quantity are you taking?")
      self.messageText.setAlignment(Qt.AlignCenter)
      layout.addWidget(self.messageText)
      self.CheckoutSpinBox = QSpinBox()
 
      self.ConfirmButton = QPushButton()
      self.ConfirmButton.setText("Confirm")
 
         
      layout.addWidget(self.CheckoutSpinBox)
      layout.addWidget(self.ConfirmButton)
 
      self.CheckoutSpinBox.valueChanged.connect(self.currentValue)
      self.setLayout(layout)
      self.setWindowTitle("Checkout")
 
      #------------------------------------------
                        #Confim Button
      #------------------------------------------
      #When the Confirm button is clicked -> Confirm Function
      ConfirmButton = self.ConfirmButton
      ConfirmButton.clicked.connect(self.ConfirmClicked)
      #------------------------------------------
      
      self.setGeometry(self.parent().x(), self.parent().y(), 
                        round(self.parent().width() / 2), 
                        round(self.parent().height() / 4))
         
   def currentValue(self):
      #Show the current value of the SpinBox in real time
      self.messageText.setText("You are taking: "+str(self.CheckoutSpinBox.value()))
 
   def ConfirmClicked(self):
      CheckoutQuantity = self.CheckoutSpinBox.value()
      print("Quantity you are taking: ", CheckoutQuantity)
      self.parent().checkout_value = CheckoutQuantity
      #self.parent().lbl.setText(f'CheckoutQuantity: {checkout_value}')
      self.parent().update_label()
      self.close()
 
 
def main():
   app = QApplication(sys.argv)
   win = MainWindow()
   win.show()
   sys.exit(app.exec_())
     
if __name__ == '__main__':
   main()
Reply
#3
Thanks for the suggestion. I'll nest my CheckoutPopup (spindemo) inside my main code if I have to, but I'm wondering if it's possible to take a variable from my AdminMenu.py and use it in my CheckoutPopup.py?

I'm trying to take the "name" variable (or TestVariable) and bring it over to my CheckoutPopup.py

Is there a way to carry the variable over to the other code or is it just better to have the CheckoutPopup nested inside my AdminMenu.py?

Snippet from AdminMenu.py
    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))
                
                #For Testing:
                global TestVariable
                TestVariable = item.data()

            print(name)
Snippet from CheckoutPopup.py:
    def currentValue(self):
     
      #Show the current value of the SpinBox in real time
      from AdminMenu import TestVariable
      self.messageText.setText("You are taking: "+str(self.CheckoutSpinBox.value()) + " " + TestVariable)
Error:
Error:
from AdminMenu import TestVariable ImportError: cannot import name 'TestVariable' from 'AdminMenu'
---------------------------------------------
Update:
---------------------------------------------
So I tried bringing the CheckoutSpinBox.value() to my AdminMenu.py but I get 0 every time. It's a step further but I need the value that the user entered once the Confirm Button is clicked (ConfirmClicked) not the default value of the spinbox (0). Is there a way to get that value the way I'm currently trying to do it?

Here's what I did in my AdminMenu.py
#----------------------------------
    #Checkout Function
    def CheckoutClicked(self):
        #Print in terminal for testing:
        print("The Checkout Button was clicked")

        from CheckoutPopup import Ui_CheckoutPopup
        x = Ui_CheckoutPopup()
        x.ConfirmClicked()
        print(x.CheckoutSpinBox.value())

        self.win = Ui_CheckoutPopup()
        self.win.show()
        #self.close()

#----------------------------------
Reply
#4
You don't have to import TestVariable
Reply
#5
(Jun-05-2022, 05:09 PM)Axel_Erfurt Wrote: You don't have to import TestVariable

What do you mean?
Then how do I call it in my other script?
Reply
#6
see https://instructobit.com/tutorial/108/Ho...-in-Python
Reply
#7
So here's what I'm trying to do.

I have two scripts: AdminMenu.py and the CheckoutPoup.py.

When the user selects an entire row(as show in the attached screenshot) the selected item's Name, and ID are carried over from the AdminMenu.py to the CheckoutPopup.py. That way I can use the item's ID in my SQL UPDATE statement and display the item's Name on the Checkout popup window so the user knows what Item they are checking out (The message/label will display something like: "You are taking: 4 Test Item").

So how do I carry over the selected item's Name and ID to the Checkout.py?
(Since I plan on doing it this way I no longer have to carry over the SpinBox value since everything will be done in the CheckoutPopup.py. But I still need to figure out how to carry the Name & ID over)

AdminMenu.py Inventory Display code snippet:
#----------------------------------------------------------------------------------------------------
#                                       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))
 
    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
        #----------------------------------
#----------------------------------------------------------------------------------------------------

Attached Files

Thumbnail(s)
   
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Validating and modifying a Spinbox pfdjhfuys 2 1,172 May-21-2023, 12:17 PM
Last Post: pfdjhfuys
  [PyQt] [Solved]How to Run GUI MsgBox From Terminal Properly Extra 4 1,695 Oct-03-2022, 11:01 PM
Last Post: Extra
  [PyQt] [Solved]Help getting variable from Function in PyQt Extra 6 1,460 Jul-06-2022, 10:19 PM
Last Post: Extra
  [Tkinter] how to celect com port from spinbox and make connect button 00alkskodi00 0 2,391 Apr-20-2020, 02:26 PM
Last Post: 00alkskodi00

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020