简体   繁体   English

从 PyQt5 中的另一个 class 访问变量

[英]Access A Variable from another class in PyQt5

In PyQt5, I've wrote a GUI.在 PyQt5 中,我编写了一个 GUI。 Basically, when a button is pressed, it open a new window, where choose an item from a list.基本上,当按下按钮时,它会打开一个新的 window,从列表中选择一个项目。 What I want is that after you close the new window, the item you chose appears as text on the first window.我想要的是,在您关闭新的 window 后,您选择的项目在第一个 window 上显示为文本。 It's a hard to explain.这很难解释。

This is the code:这是代码:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from PyQt5 import QtWidgets
from PyQt5 import QtCore 
from PyQt5 import QtGui

class Add(QtWidgets.QMainWindow):
    def __init__(self):
        super(Add, self).__init__()

        #Set The UI
        self.initUI()
        #Set The GUI Position And Size
        self.setGeometry(1050, 500, 400, 50)
        #Set The GUI Title
        self.setWindowTitle("Add")
        
    def initUI(self):
        Central = QtWidgets.QWidget(self)
        self.setCentralWidget(Central)

        self.deckButton = QtWidgets.QPushButton(self)
        self.deckButton.setText("Choose")
        self.deckButton.clicked.connect(self.open_deck_browser)

        hbox = QtWidgets.QHBoxLayout()
        hbox.addWidget(self.deckButton, 1)

        Central.setLayout(hbox)

    def open_deck_browser(self):
        self.w = SetDeck()
        self.w.show()

class SetDeck(QtWidgets.QMainWindow):
    def __init__(self):
        super(SetDeck, self).__init__()

        #Set The UI
        self.initUI()
        #Set The GUI Position And Size
        self.setGeometry(200, 200, 800, 640)
        #Set The GUI Title
        self.setWindowTitle("Choose Deck")
        
    def initUI(self):
        widAddToDeckWindow = QtWidgets.QWidget(self)
        self.setCentralWidget(widAddToDeckWindow)

        #Create The List Widget
        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.deckList.itemSelectionChanged.connect(self.show_List)
        print([x.row() for x in self.deckList.selectedIndexes()])

        #Create The Select Deck Button
        self.selectDeck = QtWidgets.QPushButton(self)
        self.selectDeck.setText("Choose")
        
        hboxCreateBottomButtons = QtWidgets.QHBoxLayout()

        hboxCreateBottomButtons.addStretch()
        hboxCreateBottomButtons.addWidget(self.selectDeck)

        #Create The Main VBox
        vboxMain = QtWidgets.QVBoxLayout()
        vboxMain.addWidget(self.deckList)
        vboxMain.addLayout(hboxCreateBottomButtons)        

        widAddToDeckWindow.setLayout(vboxMain)

    def show_List(self):
        print(repr(self.deckList.selectedItems()[0].text()))

def window():
    app = QtWidgets.QApplication(sys.argv)
    win = Add()
    win.show()
    sys.exit(app.exec_())

window()

I've tried using global variables, but it didn't work.我试过使用全局变量,但没有用。

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.首先,我建议您在命名变量时改进您的风格,因为它们使阅读更容易,例如 class 名称是名词而不是动词。

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.如果您想要 window 并要求用户提供有关如何 select 的信息,该选项随后将在主 window 中使用,那么建议使用 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.在以下示例中,这已完成,并且“选择”按钮链接到接受槽,以便它关闭 window,并且该信息可用于知道 window 的“x”按钮未关闭。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM