Search code examples
pythonlistfunctiontuplesqpainter

Providing a list to a function


I've never come across this problem until now and can't think how to proceed. I would like to know how to provide each element of a tuple to a function that wants individual parameters:

myTuple = (1,2,3,4)

def myFunction(w, x, y, z):

but calling it with:

u = myFunction(myTuple)

This is probably beside the point, but the application has to do with drawing with PyQt's QPainter and providing the coordinates in a list (mylist, in the code below):

#!/usr/bin/python3
import sys
from PyQt5.QtWidgets import QLabel, QMainWindow, QApplication
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QPixmap

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        lbl = QLabel()
        pm = QPixmap(70, 70)
        pm.fill(Qt.white)
        lbl.setPixmap(pm)
        self.setCentralWidget(lbl)
        p = QPainter(lbl.pixmap())
        p.drawLine(10,20,10,40)
        line = (10,40, 40, 50)
        p.drawLine(line)
        p.end()
        self.show()

app = QApplication(sys.argv)
win = MyWindow()
app.exec_()

Thank you for any help.


Solution

    • You can change p.drawLine(line) to p.drawLine(*line).
    • Also, you probably want to pass the line as a list() not tuple() (note that list = (1,2,3,4) is not a list().):
    #!/usr/bin/python3
    import sys
    from PyQt5.QtWidgets import QLabel, QMainWindow, QApplication
    from PyQt5.QtCore import Qt
    from PyQt5.QtGui import QPainter, QPixmap
    
    class MyWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            lbl = QLabel()
            pm = QPixmap(70, 70)
            pm.fill(Qt.white)
            lbl.setPixmap(pm)
            self.setCentralWidget(lbl)
            p = QPainter(lbl.pixmap())
            p.drawLine(10,20,10,40)
            line = [10,40, 40, 50]
            p.drawLine(*line)
            p.end()
            self.show()
    
    app = QApplication(sys.argv)
    win = MyWindow()
    app.exec_()
    

    Note

    What's the difference between lists and tuples?