2017-12-20 3 views
0

여기 내 코드가 있습니다. 나는 당신이 드롭 다운 박스를 바꿀 때 동적으로 입력을위한 QLineEdits를 더 많이 또는 적게 표시 할 수 있도록하려고 노력 중이다. 이 테스트의 단지 최신의 반복이다요소에서 동적으로 요소를 추가/제거 할 수 있습니까?

import sys 
from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, 
    QInputDialog, QApplication, QComboBox, QFrame) 

import numpy as np 


class GUI(QWidget): 

    def __init__(self): 
     super().__init__() 

     self.initgui() 

    def initgui(self): 
     # 
     # Set up GUI 
     # 
     self.setGeometry(100, 100, 400, 400) 
     self.move(300, 300) 
     combobox = QComboBox(self) 
     for i in range(1, 10, 1): 
      combobox.addItem(str(i + 1)) 
     combobox.activated[str].connect(self.comboboxchanged) 
     self.setWindowTitle("Testing Easy Setup") 
     self.show() 

    def comboboxchanged(self, text): 
     frame = QWidget(self) 
     frame.hide() 
     for num in range(0, int(text), 1): 
      QLineEdit(frame).move(60, num * 19) 
     frame.show() 

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    gui = GUI() 
    sys.exit(app.exec_()) 

답변

1

문제는 당신이 귀하의 경우 QFrame에서 부모에 대한 0, 0 위치에 배치 된 위젯에 부모를 통과 할 때의 상단에 있다는 것입니다 QComboBox 모두가 0, 0 위치에 있기 때문입니다. 적절한 것은 레이아웃을 사용하는 것입니다. 반면 위젯을 추가하기 전에 위젯을 제거해야하며, 위젯을 제거하는 함수를 만듭니다.

import sys 
from PyQt5.QtWidgets import * 

def clearLayout(lay): 
    while lay.count() > 0: 
     item = lay.takeAt(0) 
     widget = item.widget() 
     if widget: 
      widget.deleteLater() 
     del item 


class GUI(QWidget): 
    def __init__(self): 
     super().__init__() 
     self.initgui() 

    def initgui(self): 
     lay = QHBoxLayout(self) 
     vlay1 = QVBoxLayout() 
     combobox = QComboBox(self) 
     combobox.addItems([str(i) for i in range(2, 11)]) 
     vlay1.addWidget(combobox) 
     vlay1.addItem(QSpacerItem(20, 245, QSizePolicy.Minimum, QSizePolicy.Expanding)) 

     self.vlay2 = QVBoxLayout() 
     lay.addLayout(vlay1) 
     lay.addLayout(self.vlay2) 
     self.comboboxchanged(combobox.currentText()) 
     combobox.activated[str].connect(self.comboboxchanged) 
     self.setWindowTitle("Testing Easy Setup") 
     self.show() 

    def comboboxchanged(self, text): 
     clearLayout(self.vlay2) 
     for num in range(0, int(text)): 
      self.vlay2.addWidget(QLineEdit(self)) 
     self.vlay2.addItem(QSpacerItem(20, 245, QSizePolicy.Minimum, QSizePolicy.Expanding)) 

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    gui = GUI() 
    sys.exit(app.exec_()) 
+0

대단히 감사합니다! 정확히 내가 찾던 것이 아니었지만, 코드는 내가 궁극적 인 해결책을 얻는 데 필요한 것을 충분히 설명했다. –

관련 문제