K
K
Kurum2017-03-28 18:29:24
Python
Kurum, 2017-03-28 18:29:24

PyQt4 | How to refer to non-existent elements in functions?

This program creates fields and buttons, but I don't know how to refer to these elements in functions, which do not yet exist.
The start function should multiply the left field by two and output to the right field of its row.
The click function prints the number from the left margin of its row to the console.

# Python 3. PyQt4
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui


class GridLayout(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setWindowTitle('Заголовок')

        self.grid = QtGui.QGridLayout()
               

        # ПОЛЯ       
        names_pole = ['12','','7','','4','']
        pos_pole = [(0, 0), (0, 1),
                    (1, 0), (1, 1),
                    (2, 0), (2, 1)]
        j = 0
        for i in names_pole:
            self.pole = QtGui.QLineEdit(i)
            self.grid.addWidget(self.pole, pos_pole[j][0], pos_pole[j][1])
            j = j + 1      
            self.pole.textChanged.connect(self.on_start) # сигнал изм текста
        
        # КНОПКИ
        names_button = ['Copy', 'Copy', 'Copy']      
        pos_button = [(0, 3), (1, 3), (2, 3)]
        j = 0
        for i in names_button:
            self.button = QtGui.QPushButton(i)
            self.grid.addWidget(self.button, pos_button[j][0], pos_button[j][1])
            j = j + 1
            self.button.clicked.connect(self.on_click)

        self.setLayout(self.grid)
    
    def on_start(self):
        a = self.pole.text()
        b = 2*a
        self.pole.setText(str(b)) 
        print('старт')
    
    def on_click(self):
        a = self.pole.text()
        print(a,'клик')

app = QtGui.QApplication(sys.argv)
qb = GridLayout()
qb.show()
sys.exit(app.exec_())

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail, 2017-04-12
@mFoxRU

Store references to objects in a dictionary. A good approach is to first create all the elements, and then connect them.
In addition, here

for i in names_pole:
            self.pole = QtGui.QLineEdit(i)

self.pole is overwritten, so in functions it will always refer to the last created lineedit. Same thing with self.button.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question