[英]Type values in lineedit and then add it to a comboBox by clicking a button? PyQt4
我想通過單擊按鈕(一次一個值)將lineedit中鍵入的多個值添加到組合框。 我的示例代碼如下:
import os, sys
import PyQt4
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Example(QWidget):
def __init__(self, parent = None):
super().__init__()
self.grid = QGridLayout()
self.setLayout(self.grid)
btn = QPushButton()
le = QLineEdit()
combo = QComboBox()
self.grid.addWidget(btn, 0, 0)
self.grid.addWidget(le, 0 , 1)
self.grid.addWidget(combo, 0, 2)
self.show()
def main():
app = QApplication(sys.argv)
main = Example()
main.show()
sys.exit(app.exec_())
main()
如果有人知道該怎么做,請告訴我。 感謝!
解決方案很簡單,您應該分析的第一件事是在哪個事件發生之前執行操作,在這種情況下,當發出喀噠聲時,要連接一個插槽並在其中管理邏輯。 要獲取文本,請使用QLineEdit
的text()
方法,然后使用addItem()
方法將其添加到QComboBox
。我添加了一個小的邏輯來驗證並且不能添加非空文本,也不要重復這些項目
class Example(QWidget):
def __init__(self, parent = None):
super().__init__()
self.grid = QGridLayout()
self.setLayout(self.grid)
self.btn = QPushButton()
self.le = QLineEdit()
self.combo = QComboBox()
self.grid.addWidget(self.btn, 0, 0)
self.grid.addWidget(self.le, 0 , 1)
self.grid.addWidget(self.combo, 0, 2)
self.btn.clicked.connect(self.onClicked)
def onClicked(self):
text = self.le.text()
# the text is not empty
if text != "":
# get items of combobox
items = [self.combo.itemText(i) for i in range(self.combo.count())]
# Add if there is no such item
if text not in items:
self.combo.addItem(text)
只能在所創建方法的范圍內訪問變量,因此不適合僅使窗口小部件成為變量,而使類的屬性適用,因為在類的任何方法中都可以訪問它們。 為此,我們只能放自我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.