K
K
kapit2018-10-13 22:57:10
Python
kapit, 2018-10-13 22:57:10

How to dynamically resize QLineEdit in QGridLayput grid?

5bc24a8dc6b77717500257.jpeg
In the demonstration, QLineEdit destroys the entire construction of QGridLayput, but I would like QLineEdit to behave the same way as QLabel. How to achieve this?

class winShow(QtWidgets.QWidget):
  def __init__(self):
    super(winShow, self).__init__()
    self.allotted = list()
    self.dict_widgets = dict()
    self.create_grid()

  def create_grid(self):
    self.layout = QtWidgets.QVBoxLayout()
    self.gridbox = QtWidgets.QGridLayout()
    n = ['name_label_{}'.format(str(x)) for x in range(9)]
    ne = ['name_edit_{}'.format(str(x)) for x in range(9)]
    t = ['12', '13', '14', '34', '10', '54', '67', '43', '34']
    p = [(i,j) for i in range(3) for j in range(3)]

    for name, text, position in zip(n, t, p):
      self.dict_widgets[name] = QtWidgets.QLabel(text)
      self.gridbox.addWidget(self.dict_widgets[name], *position)
      self.dict_widgets[name].setObjectName(name)
      self.allotted.append(name)

    for name, text, position in zip(ne, t, p):
      self.dict_widgets[name] = QtWidgets.QLineEdit(text)
      self.gridbox.addWidget(self.dict_widgets[name], *position)
      self.dict_widgets[name].hide()

    self.layout.addLayout(self.gridbox)
    self.layout.addStretch(10)
    self.setLayout(self.layout)
    qApp.installEventFilter(self)

  def eventFilter(self, obj, event):
    if event.type() == QEvent.MouseButtonPress:
      if obj.objectName() in self.allotted:
        name = obj.objectName()
        for widget in self.dict_widgets:
          if 'edit' in widget: 
            self.dict_widgets[widget].hide()
          elif 'label' in widget: 
            self.dict_widgets[widget].show()
        nl = name.split('_')
        self.dict_widgets[name].hide()
        self.dict_widgets['{}_edit_{}'.format(nl[0], nl[2])].show()

    return QWidget.eventFilter(self,obj,event)

if __name__ == '__main__':
  app = QtWidgets.QApplication(sys.argv)
  window = winShow()
  window.resize(200, 50)
  window.show()
  sys.exit(app.exec_())

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yeedab, 2018-10-18
@kapit

It is better, of course, to use a normal table, for example, QTreeWidget.
But it's possible like this:

class MineLineEdit(QtWidgets.QLineEdit):
  def __init__(self, text, parent=None):
    super().__init__(text, parent)
    self.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred))
    self.parent = parent

  def sizeHint(self):
    if not self.parent:
      return super().sizeHint()
    print(self.parent.size())
    return self.parent.size()

<...>

      self.dict_widgets[name] = MineLineEdit(text, self.dict_widgets[name.replace('edit', 'label')])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question