如何根据对话框中的事件填充主窗口中的列表

2024-10-02 12:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用PyQt5,在那里我尝试创建团队,并在联赛系统上工作。你知道吗

我已经创建了打开对话框的操作按钮。 我想根据从对话框窗口中选择的团队名称填充数据库中的某些列表。你知道吗

我想我被困住了,因为我不明白如何在两者之间沟通。你知道吗

当我尝试添加新团队时,我希望主窗口中的所有列表都得到适当的填充。但如何将此信息从对话框传递到主窗口,并在之后立即关闭对话框?你知道吗

代码如下:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QInputDialog, QLineEdit, QDialog, QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QApplication, QComboBox
import sqlite3

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        #removed because too big
        #full code in link

    def setupEvents(self, MainWindow):
        self.actionNew_Team.triggered.connect(self.newTeam)
        self.actionOpen_Team.triggered.connect(self.openTeam)

    def newTeam(self, MainWindow):
        n = NewTeamDialog()
        n.exec_()

    def openTeam(self, MainWindow):
        o = OpenTeamDialog()
        o.exec_()

    def saveTeam(self, MainWindow):
        pass

class NewTeamDialog(QDialog):
    def __init__(self):
        super(NewTeamDialog, self).__init__()
        self.setWindowTitle("Create New Team")
        self.setFixedWidth(300)
        self.setFixedHeight(100)
        self.nameInput = QLineEdit()
        self.nameInput.setPlaceholderText("Enter Team Name")
        self.addBtn = QPushButton()
        self.addBtn.setText("Add Team")
        self.addBtn.clicked.connect(self.addTeam)
        layout = QVBoxLayout()
        layout.addWidget(self.nameInput)
        layout.addWidget(self.addBtn)
        self.setLayout(layout)

    def addTeam(self):
        name = self.nameInput.text()
        conn = sqlite3.connect("example.db")
        c = conn.cursor()
        c.execute('SELECT * FROM batsmen')
        print(c.fetchall())
        conn.close()
        self.close()

链接:https://www.paste.org/99817


Tags: importself列表defconnect团队connteam
1条回答
网友
1楼 · 发布于 2024-10-02 12:37:43

这就是你要找的吗?你知道吗

您正在通过方法创建OpenTeamDialogNewTeamDialog类,但是对话框对Window类一无所知,因此在初始化它们时必须将其作为参数传递,以便可以访问它的所有小部件。你知道吗

这是假设您的数据库是相同的,即有以下表格: 全能选手、击球手、保龄球手、守门员和一个名为“团队”的栏位:

另外,我正在另一个类中设置UI,所以除了UI\u MainWindow类中的QtDesigner提供的UI部分之外,我会删除任何东西。你知道吗

很可能有更好的方法来实现这一点,但这只是一个基于您的需求的粗略设计。你知道吗

class Window(QtWidgets.QMainWindow,Ui_MainWindow):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.setupUi(self)
        self.setupEvents()

    def setupEvents(self):
        self.actionNew_Team.triggered.connect(self.newTeam)
        self.actionOpen_Team.triggered.connect(self.openTeam)

    def newTeam(self):
        n = NewTeamDialog(self)
        n.exec_()

    def openTeam(self):
        o = OpenTeamDialog(self)
        o.exec_()

    def saveTeam(self):
        pass

class NewTeamDialog(QtWidgets.QDialog):
    def __init__(self,window,parent = None):
        super(NewTeamDialog, self).__init__(parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.window = window
        self.setWindowTitle("Create New Team")
        self.setFixedWidth(300)
        self.setFixedHeight(100)

        self.dropDown_TeamType = QtWidgets.QComboBox()
        #Added dropdown to choose which team goes in the team type
        self.dropDown_TeamType.addItems(["ALLROUNDERS", "BATSMEN", "BOWLERS","WICKETKEEPER" ])
        self.nameInput = QtWidgets.QLineEdit()
        self.nameInput.setPlaceholderText("Enter Team Name")

        self.addBtn = QtWidgets.QPushButton()
        self.addBtn.setText("Add Team")
        self.addBtn.clicked.connect(self.addTeam)
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.dropDown_TeamType)
        layout.addWidget(self.nameInput)
        layout.addWidget(self.addBtn)
        self.setLayout(layout)

    def addTeam(self):
        name = self.nameInput.text()
        team_type = self.dropDown_TeamType.currentText()
        conn = sqlite3.connect("example.db")
        c = conn.cursor()
        #adds team to the database using the current selected dropdown item
        c.execute("SELECT TEAM FROM {0} WHERE TEAM=?;".format(team_type),(name.title(),))
        exists = c.fetchall()
        if not exists:
            c.execute("INSERT INTO {0} VALUES('{1}');".format(team_type,name.title()))
            conn.commit()
            conn.close()
        conn.close()
        self.close()
        if team_type == "BATSMEN":
            item = QtWidgets.QListWidgetItem(name)
            self.window.listWidget_3.addItem(item)
        elif team_type == "ALLROUNDERS":
            item = QtWidgets.QListWidgetItem(name)
            self.window.listWidget_4.addItem(item)
        elif team_type == "BOWLERS":
            item = QtWidgets.QListWidgetItem(name)
            self.window.listWidget_5.addItem(item)
        elif team_type == "WICKETKEEPER":
            item = QtWidgets.QListWidgetItem(name)
            self.window.listWidget_6.addItem(item)

class OpenTeamDialog(QtWidgets.QDialog):
    def __init__(self, window, parent = None):
        super(OpenTeamDialog, self).__init__(parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.window = window
        self.setWindowTitle("Open Saved Team")
        self.setFixedWidth(300)
        self.setFixedHeight(100)
        self.dropDown_TeamType = QtWidgets.QComboBox()
        self.dropDown_TeamType.addItems(["ALLROUNDERS", "BATSMEN", "BOWLERS","WICKETKEEPER" ])
        self.dropDown = QtWidgets.QComboBox()
        self.dropDown_TeamType.currentIndexChanged.connect(self.itemChanged)
        self.addBtn = QtWidgets.QPushButton()
        self.addBtn.setText("Add Team")
        self.addBtn.clicked.connect(self.openTeam)
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.dropDown_TeamType)
        layout.addWidget(self.dropDown)
        layout.addWidget(self.addBtn)
        self.setLayout(layout)
        conn = sqlite3.connect("example.db")
        conn.row_factory = lambda cursor, row: row[0]
        c = conn.cursor()
        c.execute("SELECT TEAM FROM ALLROUNDERS")
        result = c.fetchall()
        self.dropDown.addItems(result)

    def itemChanged(self):
        #adds all items from the database 'Team' column to drop down whenever it changes
        team_type = self.dropDown_TeamType.currentText()
        self.dropDown.clear()
        conn = sqlite3.connect("example.db")
        conn.row_factory = lambda cursor, row: row[0]
        c = conn.cursor()
        c.execute("SELECT TEAM FROM {0}".format(team_type))
        result = c.fetchall()
        self.dropDown.addItems(result)
        conn.close()

    def openTeam(self):
        team_type = self.dropDown_TeamType.currentText()
        team_name = self.dropDown.currentText()
        self.close()
        if team_type == "BATSMEN":
            item = QtWidgets.QListWidgetItem(team_name)
            self.window.listWidget_3.addItem(item)
        elif team_type == "ALLROUNDERS":
            item = QtWidgets.QListWidgetItem(team_name)
            self.window.listWidget_4.addItem(item)
        elif team_type == "BOWLERS":
            item = QtWidgets.QListWidgetItem(team_name)
            self.window.listWidget_5.addItem(item)
        elif team_type == "WICKETKEEPER":
            item = QtWidgets.QListWidgetItem(team_name)
            self.window.listWidget_6.addItem(item)

class EvaluateDialog(QtWidgets.QDialog):
    pass

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = Window()
    MainWindow.show()
    sys.exit(app.exec_())

下面是一个.py文件,可用于创建相同的数据库:

import sqlite3

def createTables():
    connection = sqlite3.connect("example.db")
    connection.execute("CREATE TABLE ALLROUNDERS(TEAM TEXT NOT NULL)")
    connection.execute("CREATE TABLE BATSMEN(TEAM TEXT NOT NULL)")
    connection.execute("CREATE TABLE BOWLERS(TEAM TEXT NOT NULL)")
    connection.execute("CREATE TABLE WICKETKEEPER(TEAM TEXT NOT NULL)")
    connection.execute("INSERT INTO ALLROUNDERS VALUES(?)",('Empty',))
    connection.execute("INSERT INTO BATSMEN VALUES(?)",('Empty',))
    connection.execute("INSERT INTO BOWLERS VALUES(?)",('Empty',))
    connection.execute("INSERT INTO WICKETKEEPER VALUES(?)",('Empty',))
    connection.commit()
    result = connection.execute("SELECT * FROM BATSMEN")
    connection.close()


createTables()

相关问题 更多 >

    热门问题