Discovering the clickable widget index in pyqt4: A beginner's guide

In my application, I am working on creating multiple widget orders using a list of dictionaries to create a list of widgets. I have implemented a mouse release event for clickable widgets, but I am facing issues in identifying the clicked widget index. Can anyone provide guidance on how to determine the index of the clicked widget sender?

from datetime import datetime
from PyQt4 import QtCore, QtGui
from functools import partial

class Orders(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Orders, self).__init__(parent)
        
        Online_order_dict = [{"Date":"jan-24-2019","Id":"#175","Amount":"191 rs", "Shopping":"Online","Order_City":"Hyderbad","Order_State":"TELANGANA"},{"Date":"jan-25-2019","Id":"#186","Amount": "200 Rs", "Shopping":"Online","Order_City":"Hyderbad","Order_State":"TELANGANA"},{"Date":"jan-29-2019","Id":"#188","Amount": "250 Rs", "Shopping":"Online","Order_City":"Hyderbad","Order_State":"TELANGANA"},{"Date":"jan-25-2019","Id":"#176","Amount": "200 Rs", "Shopping":"Online",
        "Order_City":"Hyderbad","Order_State":"TELANGANA"},{"Date":"jan-28-2019","Id":"#201","Amount": "250 Rs", "Shopping":"Online","Order_City":"Hyderbad","Order_State":"TELANGANA"}]

        self.qvw1 = QtGui.QWidget()
        self.scrollArea = QtGui.QScrollArea(widgetResizable=True)
        self.scrollArea.setWidget(self.qvw1)

        self.online_order_hbox = QtGui.QVBoxLayout(self.qvw1)
        self.online_label = QtGui.QPushButton("Online Order")
        self.online_label.setStyleSheet("QPushButton{ background-color: #FF8C00; color: white;outline : None;}")
        self.online_order_hbox.addWidget(self.online_label,QtCore.Qt.AlignTop)
        self.qvw1.setFixedWidth(round((550)))
        
        for i in Online_order_dict:
            self.w1 = QtGui.QWidget()
            self.w1_vbox=QtGui.QVBoxLayout(self.w1)
            self.hline1 = QtGui.QFrame();self.hline1.setFrameShape(QtGui.QFrame.HLine)
            self.date_label1 = QtGui.QLabel(i["Date"]  + "   " + i["Id"], alignment= QtCore.Qt.AlignCenter,objectName="small")
            self.amount = QtGui.QLabel("Amount:" + i["Amount"])
            self.shopping = QtGui.QLabel("Shopping :" + i["Shopping"])
            self.ordercity = QtGui.QLabel("Order City :" + i["Order_City"])
            self.orderstate = QtGui.QLabel("Order State :" +i["Order_State"])
            self.w1_vbox.addWidget(self.date_label1)
            self.w1_vbox.addWidget(self.amount)
            self.w1_vbox.addWidget(self.shopping)
            self.w1_vbox.addWidget(self.ordercity)
            self.w1_vbox.addWidget(self.orderstate)
            self.w1_vbox.addWidget(self.hline1)
            self.online_order_hbox.addWidget(self.w1)

        self.setCentralWidget(self.scrollArea)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)

    settingobj= Orders()
    settingobj.show()
    settingobj.showFullScreen()
    sys.exit(app.exec_())

Answer №1

As an application becomes more complex, it is advisable to implement the specialization strategy. This involves creating classes with specific responsibilities, such as a class that emits a signal when pressed with the mouse. The class should contain all necessary information for easy access.

from PyQt4 import QtCore, QtGui

class InfoWidget(QtGui.QWidget):
    clicked = QtCore.pyqtSignal()

    def __init__(self, info, parent=None):
        super(InfoWidget, self).__init__(parent)
        self._info = info

        date_label = QtGui.QLabel("{}   {}".format(info["Date"], info["Id"]), alignment= QtCore.Qt.AlignCenter, objectName="small")
        amount_label = QtGui.QLabel("Amount:{}".format(info["Amount"]))
        shopping_label = QtGui.QLabel("Shopping :{}".format(info["Shopping"]))
        ordercity_label = QtGui.QLabel("Order City :{}".format(info["Order_City"]))
        orderstate_label = QtGui.QLabel("Order State :{}".format(info["Order_State"]))
        hline = QtGui.QFrame(frameShape=QtGui.QFrame.HLine)

        lay = QtGui.QVBoxLayout(self)
        lay.addWidget(date_label)
        lay.addWidget(amount_label)
        lay.addWidget(shopping_label)
        lay.addWidget(ordercity_label)
        lay.addWidget(orderstate_label)
        lay.addWidget(hline)

    @property
    def info(self):
        return self._info    

    def mousePressEvent(self, event):
        self.clicked.emit()
        super(InfoWidget, self).mousePressEvent(event)

class Orders(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Orders, self).__init__(parent)
        Online_order_dict = [
            {"Date" : "jan-24-2019", "Id" : "#175", "Amount" : "191 rs", "Shopping" : "Online", "Order_City" : "Hyderbad", "Order_State" : "TELANGANA"},
            {"Date" : "jan-25-2019", "Id" : "#186", "Amount" : "200 Rs", "Shopping" : "Online", "Order_City" : "Hyderbad", "Order_State" : "TELANGANA"},
            {"Date" : "jan-29-2019", "Id" : "#188", "Amount" : "250 Rs", "Shopping" : "Online", "Order_City" : "Hyderbad", "Order_State" : "TELANGANA"},
            {"Date" : "jan-25-2019", "Id" : "#176", "Amount" : "200 Rs", "Shopping" : "Online", "Order_City" : "Hyderbad", "Order_State" : "TELANGANA"},
            {"Date" : "jan-28-2019", "Id" : "#201", "Amount" : "250 Rs", "Shopping" : "Online", "Order_City" : "Hyderbad", "Order_State" : "TELANGANA"}
        ]

        self.qvw1 = QtGui.QWidget()
        self.scrollArea = QtGui.QScrollArea(widgetResizable=True)
        self.scrollArea.setWidget(self.qvw1)

        online_order_hbox = QtGui.QVBoxLayout(self.qvw1)
        self.online_label = QtGui.QPushButton("Online Order")
        self.online_label.setStyleSheet("QPushButton{ background-color: #FF8C00; color: white;outline : None;}")
        online_order_hbox.addWidget(self.online_label,QtCore.Qt.AlignTop)
        self.qvw1.setFixedWidth(550)

        for i in Online_order_dict:
            w = InfoWidget(i)
            w.clicked.connect(self.on_info_clicked)
            online_order_hbox.addWidget(w)
        self.setCentralWidget(self.scrollArea)

    @QtCore.pyqtSlot()
    def on_info_clicked(self):
        w = self.sender()
        print(w.info)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    settingobj= Orders()
    settingobj.showFullScreen()
    sys.exit(app.exec_())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to store and validate user input in Python to avoid duplicate entries?

Is there a way to create a feature where users can input one word at a time and press enter, and if they repeat a word they've already entered, the system will notify them of the error but still allow them to add new words? ...

Encountering an issue with Python: "IndexError: list index out of range"

I can't figure out what I did wrong. names = ["paris capital", "london capital", "berlin capital"] for i in range(0,3): city = names[i+1] print(city) Mistake: File "C:\Users\Utilisateur\PycharmProjects\myfirstproject&bso ...

Is there a Python framework that specializes in serving images?

My iOS app project requires a backend server capable of efficiently handling image files and dynamic operations like interacting with a data store such as Redis. Python is my preferred language for the backend development. After exploring various Python w ...

Retrieve the value associated with the most recent date recorded in the index column

Here is the current layout of my table: Category 4/1/2022 5/1/2022 6/1/2022 1Y Min X 10 05 12 05 Y 18 20 09 09 Z 02 09 12 02 I am looking to include a new column titled "Bps away from 1Y Min" which will be calculated by subtracting the value a ...

Transforming a uint8 array into a visual image

Currently, I am facing a challenge in converting a uint8 array representing a 48x48 image into the actual image file (jpg/jpeg/gif) of the same dimensions. My initial approach involved converting the array data to binary and then saving it to a file using ...

Selenium keeps displaying the error "Error: element is not clickable" while attempting to input text

I have been trying to automate interactions with elements on Soundcloud's website using Selenium, but I am facing difficulties when attempting to interact with the input tags. Whenever I try to write in the input tag with the class "headerSearch__inpu ...

Issue: Python Selenium ChromeDriver Chrome TypeError: Cannot Call 'Module'Description: When attempting to use Selenium Python with ChromeDriver to control Chrome

Currently, I am working on a project to create a spam bot for Google Forms in order to generate random submissions for my homework. However, I have encountered an error which reads: TabError: inconsistent use of tabs and spaces in indentation. Please note ...

What is the best way to broadcast messages to multiple clients using Flask-SocketIO?

Currently, I am diving into the world of Flask-SocketIO with a simple chat application in mind. However, I've encountered an issue where messages are not being received by anyone except for the user in the browser. Here's the Python/Flask code sn ...

Selenium paired with the innovative Brave browser, a Chromium-based platform with the latest Version 1.33.106 Chromium: 96.0.4664.110 (Official Build) (64-bit)

I have just started learning Python and am currently working on a browser automation project using Selenium. Currently, I am using Brave version 96.0.4664.45 but facing issues with my Chrome driver not functioning properly. On the other hand, geckodriver i ...

Python script in PowerShell has arguments that include double quotes and whitespace

I am attempting to execute a python script using PowerShell. Within the python script, I am trying to include a command line argument with double quotes and whitespace, but it is not working as expected. It seems like there may be an issue with PowerShell. ...

Is there a way to verify the status of a checkbox in Selenium using Python?

When attempting to determine the status of a checkbox using a method that returns a boolean value, I am encountering a problem where it always returns false regardless of whether the checkbox is checked or unchecked. def checkbox_status(self): ch ...

"Setting up the latest version of Selenium along with ChromeDriver and Headless Chrome driver for automated testing

Utilizing Python and Selenium with AWS Lambdas for web crawling has been a part of my workflow. After upgrading Python to version 3.11 and Selenium to version 4.18.0, I encountered issues that caused my crawlers to cease functioning properly. Below is the ...

Leveraging a collection of URLs with Python Selenium

I have a text document containing a list of URLs called all_urls.txt. Each URL in the file is listed on its own line. I am looking to utilize Selenium with Python in order to extract specific data from each of these URLs. Currently, my approach involves pr ...

Tips for extracting real-time data from a map using JavaScript scraper

As a new Python user, I am looking to scrape data from the following website: The challenge I'm facing is that the data on the website is dynamically generated. I have tried different solutions but none of them seem to work. With Selenium, I usually ...

Is there an excess memory consumption associated with objects encapsulated by pybind11?

I'm curious about the potential memory implications of using C++ classes or structs wrapped by pybind11. Let's explore a simple scenario: struct Person { std::string name; int age; } // Demonstrating basic bindings pybind11::class_<Perso ...

Discover nearby connections within a pandas dataframe

In my dataset, I have information about bicycles including the store they are sold in and details about the model. My goal is to analyze the sales numbers of different bicycle models within each store. To do this, I need to follow these steps: Firstly, g ...

Dividing a roster of creases into training and validation subsets

After developing code to split data into 7 folds, I now have a list of lists containing these folds. My next goal is to further divide each fold into training and validation sets and store them as data frames. Despite my efforts using manual methods, Grou ...

What is the best way to insert a list of objects from a BaseModel class into a database using SQL Alchemy and FastApi?

I am looking to dynamically insert rows into a table named "computers" for some of its columns, with the column names not known in advance hence the need for dynamic insertion. To achieve this, I have created a BaseModel class called "ColumnIn" that consi ...

What is the best method for storing information in a Cassandra table using Spark with Python?

I am currently working on developing a consumer-producer application. In this application, the Producer generates data on specific topics. The Consumer consumes this data from the same topic, processes it using the Spark API, and stores it in a Cassandra ...

Exporting Python Pandas Data Frame to an HTML file

I'm attempting to save a Python Pandas Data Frame as an HTML page. I also want to ensure that the table can be filtered by the value of any column when saved as an HTML table. Do you have any suggestions on how to accomplish this? Ultimately, I want t ...