First of all, I recommend you improve your style when naming variables as they make reading easier, for example that the class name are nouns and not a verb.
Getting to the bottom of the problem, never use (or try to use) global variables as they cause silent bugs if there is a better option and you don't understand how it works. In the case that you want a window where you ask the user to provide information on how to select an option that will then be used in the main window then it is advisable to use a QDialog. In the following example, this is done and the "Choose" button is linked to the accept slot so that it closes the window, and that information can be used to know that the "x" button of the window was not closed. Also I have created a property that has the selected text.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
self.setGeometry(1050, 500, 400, 50)
self.setWindowTitle("Add")
def initUI(self):
central = QtWidgets.QWidget(self)
self.setCentralWidget(central)
self.deckButton = QtWidgets.QPushButton()
self.deckButton.setText("Choose")
self.deckButton.clicked.connect(self.open_deck_browser)
box = QtWidgets.QVBoxLayout(central)
box.addWidget(self.deckButton)
self.label = QtWidgets.QLabel()
box.addWidget(self.label)
self.label.hide()
def open_deck_browser(self):
dialog = DeckDialog()
if dialog.exec_() == QtWidgets.QDialog.Accepted:
self.label.show()
self.label.setText(dialog.selected_text)
class DeckDialog(QtWidgets.QDialog):
def __init__(self):
super(DeckDialog, self).__init__()
self.initUI()
self.setGeometry(200, 200, 800, 640)
self.setWindowTitle("Choose Deck")
def initUI(self):
self.deckList = QtWidgets.QListWidget()
self.deckList.insertItem(0, "Hello")
self.deckList.insertItem(1, "Hi")
self.deckList.insertItem(2, "Hello There")
self.deckList.item(0).setSelected(True)
self.selectDeck = QtWidgets.QPushButton(self)
self.selectDeck.setText("Choose")
hboxCreateBottomButtons = QtWidgets.QHBoxLayout()
hboxCreateBottomButtons.addStretch()
hboxCreateBottomButtons.addWidget(self.selectDeck)
vboxMain = QtWidgets.QVBoxLayout(self)
vboxMain.addWidget(self.deckList)
vboxMain.addLayout(hboxCreateBottomButtons)
self.selectDeck.clicked.connect(self.accept)
@property
def selected_text(self):
items = self.deckList.selectedItems()
if items:
return items[0].text()
return ""
def main():
app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…