从另一个QMainWindow打开一个QMainWindow

时间:2019-11-20 18:40:13

标签: python-3.x oop pyqt5

我在理解如何从另一个打开一个QMainWindow时遇到问题。我希望在按下第一个窗口中的按钮时打开第二个窗口。但是我不知道该怎么做,因为窗口类是用不同的方式编写的。

当我尝试将具有第一个窗口的文件中的第二个窗口导入Main()类时,当我运行第一个文件时,第二个窗口开始打开,甚至看不到第一个窗口

第一个窗口:

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):

    def openWindow(self):

        blank




    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(600, 400)
        MainWindow.setMinimumSize(QtCore.QSize(600, 400))
        MainWindow.setMaximumSize(QtCore.QSize(600, 400))
        font = QtGui.QFont()
        font.setPointSize(16)
        MainWindow.setFont(font)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.splitter = QtWidgets.QSplitter(self.centralwidget)
        self.splitter.setGeometry(QtCore.QRect(170, 20, 260, 371))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth())
        self.splitter.setSizePolicy(sizePolicy)
        self.splitter.setOrientation(QtCore.Qt.Vertical)
        self.splitter.setObjectName("splitter")
        self.pushButton = QtWidgets.QPushButton(self.splitter)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())

        self.pushButton.setSizePolicy(sizePolicy)
        self.pushButton.setMaximumSize(QtCore.QSize(260, 90))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")

        #self.pushButton.clicked.connect(self.openWindow)
        #this is the button by pressing which i want to open second window





        self.pushButton_2 = QtWidgets.QPushButton(self.splitter)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
        self.pushButton_2.setSizePolicy(sizePolicy)
        self.pushButton_2.setMaximumSize(QtCore.QSize(260, 90))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")



        self.pushButton_4 = QtWidgets.QPushButton(self.splitter)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
        self.pushButton_4.setSizePolicy(sizePolicy)
        self.pushButton_4.setMaximumSize(QtCore.QSize(260, 90))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setObjectName("pushButton_4")

        self.pushButton_3 = QtWidgets.QPushButton(self.splitter)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
        self.pushButton_3.setSizePolicy(sizePolicy)
        self.pushButton_3.setMaximumSize(QtCore.QSize(260, 90))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setObjectName("pushButton_3")

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Просмотр базы"))
        self.pushButton_2.setText(_translate("MainWindow", "Выдача/Принятие книг"))
        self.pushButton_4.setText(_translate("MainWindow", "Внести книги в базу"))
        self.pushButton_3.setText(_translate("MainWindow", "Редактировать список \nклассов"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

第二个窗口:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtPrintSupport import *
import sys
import sqlite3
import time
import os

from PyQt5 import QtCore, QtGui, QtWidgets

from test2 import Ui_Dialog
from searchdialog import Ui_Dialogg

from edit import Ui_Dialoge


class Main(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(Main, self).__init__(*args, **kwargs)

        self.conn = sqlite3.connect("booksbase.db")
        self.c = self.conn.cursor()
        self.c.execute("CREATE TABLE IF NOT EXISTS books(title TEXT,subject TEXT,grade INTEGER,author TEXT,year INTEGER, amount INTEGER)")
        self.c.close()

        self.setWindowTitle("Books base")
        self.setMinimumSize(800, 600)

        file_menu = self.menuBar().addMenu("&File")

        help_menu = self.menuBar().addMenu("&About")

        self.tableWidget = QTableWidget()
        self.setCentralWidget(self.tableWidget)
        self.tableWidget.setAlternatingRowColors(False)
        self.tableWidget.setColumnCount(6)
        self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
        self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
        self.tableWidget.verticalHeader().setVisible(False)
        self.tableWidget.verticalHeader().setCascadingSectionResizes(True)
        self.tableWidget.verticalHeader().setStretchLastSection(False)
        header = self.tableWidget.horizontalHeader()
        header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(6, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)


        self.tableWidget.setHorizontalHeaderLabels(("Заголовок", "Предмет", "Класс", "Автор","Год", "Колличество"))

        self.tableWidget.itemDoubleClicked.connect(self.print)

        toolbar = QToolBar()
        toolbar.setMovable(False)
        self.addToolBar(toolbar)

        statusbar = QStatusBar()
        self.setStatusBar(statusbar)

        btn_ac_adduser = QAction(QIcon("icon/add1.jpg"), "Add Student", self)   #add student icon
        btn_ac_adduser.triggered.connect(self.insert)
        btn_ac_adduser.setStatusTip("Add Student")
        toolbar.addAction(btn_ac_adduser)

        btn_ac_search = QAction(QIcon("icon/s1.png"), "Search", self)  #search icon
        btn_ac_search.triggered.connect(self.search)
        btn_ac_search.setStatusTip("Search User")
        toolbar.addAction(btn_ac_search)



        adduser_action = QAction(QIcon("icon/add1.jpg"),"Insert Student", self)
        adduser_action.triggered.connect(self.insert)
        file_menu.addAction(adduser_action)

        searchuser_action = QAction(QIcon("icon/s1.png"), "Search Student", self)
        searchuser_action.triggered.connect(self.search)
        file_menu.addAction(searchuser_action)



        about_action = QAction(QIcon("icon/i1.png"),"Developer", self)  #info icon
        about_action.triggered.connect(self.about)
        help_menu.addAction(about_action)

    def loaddata(self):
        self.connection = sqlite3.connect("booksbase.db")
        query = "SELECT * FROM books"
        result = self.connection.execute(query)
        self.tableWidget.setRowCount(0)
        for row_number, row_data in enumerate(result):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number, QTableWidgetItem(str(data)))
        self.connection.close()

    def insert(self):
        Dialog = QtWidgets.QDialog()
        ui = Ui_Dialog()
        ui.setupUi(Dialog)
        Dialog.exec_()
        print("now")
        self.loaddata()


    def search(self):
        Dialog = QtWidgets.QDialog()
        ui = Ui_Dialogg()
        ui.setupUi(Dialog)
        Dialog.exec_()




    def print(self):
        row = self.tableWidget.currentRow()
        col = self.tableWidget.item(row,0)
        title = col.text()

        col = self.tableWidget.item(row,1)
        subject = col.text()

        col = self.tableWidget.item(row,2)
        grade = col.text()

        col = self.tableWidget.item(row,3)
        author = col.text()

        col = self.tableWidget.item(row,4)
        year = col.text()

        col = self.tableWidget.item(row,5)
        amount = col.text()

        print(title, subject, grade, author, year, amount)

        Dialog = QtWidgets.QDialog()
        ui = Ui_Dialoge()
        ui.setupUi(Dialog, title, subject, grade, author, year, amount)
        Dialog.exec_()
        self.loaddata()




app = QApplication(sys.argv)
if(QDialog.Accepted == True):
    window = Main()
    window.show()
    window.loaddata()
sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

问题在于,您为第二个窗口导入的文件试图运行其最后一个块:

app = QApplication(sys.argv)
if(QDialog.Accepted == True):
    window = Main()
    window.show()
    window.loaddata()
sys.exit(app.exec_())

导入文件(模块)时,将处理其所有可执行语句;简单来说,def之外的所有内容都将执行,包括模块自己的导入,函数调用,try / except块,for / while循环以及任何类中的所有语句定义。

由于您要检查QDialog.Accepted(这是一个常量),因此该语句显然是正确的,因此如果执行block,则会初始化并显示窗口。

从第二个文件中删除该块,它将按预期工作。

无论如何,有关该代码的两个注释:

  • 每个基于PyQt的程序应该只存在一个QApplication实例;因此,上述代码实际上在大多数情况下可能会崩溃;
  • 如前所述,QDialog.Accepted是一个常量,其值为1,因此if语句没有多大意义(它与{{1}相同) });该常数及其相反的if True == True:通常仅在根据QDialog.exec()调用的返回值进行检查时使用。