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

时间:2019-07-31 19:08:41

标签: python pyqt pyqt5

我正在使用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()

LINK:https://www.paste.org/99817

1 个答案:

答案 0 :(得分:0)

这是您要寻找的吗?

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

这是假设您的数据库是相同的含义,其中包含以下表格: ALLROUNDERS,BATSMEN,BOWLERS,WICKETKEEPER和一个名为TEAM的字段列:

我还要在另一个类中设置UI,以便删除您从QtDesigner的Ui_MainWindow类中获得的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()