Python 属性错误:模块';PyQt5.QtCore';没有属性';插槽';

Python 属性错误:模块';PyQt5.QtCore';没有属性';插槽';,python,pyqt5,Python,Pyqt5,我还是python新手,不知道如何在PyQt5中正确连接信号。我下面的代码是用PyQt4编写的,我想把它转换成新的标准。(基本上我是在一个不同的环境中起草的,现在我正试图让它在这台机器上工作) 如何将gui元素正确连接到每个函数?在我通过以下方式连接按钮元件之前: @QtCore.Slot() def on_pushButtonSolution_clicked(self): print('Total Solutions to Display {}'.format(self.total_q

我还是python新手,不知道如何在PyQt5中正确连接信号。我下面的代码是用PyQt4编写的,我想把它转换成新的标准。(基本上我是在一个不同的环境中起草的,现在我正试图让它在这台机器上工作)

如何将gui元素正确连接到每个函数?在我通过以下方式连接按钮元件之前:

@QtCore.Slot()
def on_pushButtonSolution_clicked(self):
    print('Total Solutions to Display {}'.format(self.total_questions))
为了连接菜单项,我在
\uuuu init\uuuu
中称之为:

self.actionNew.triggered.connect(self.MenuNew)
self.actionNew.setShortcut("Ctrl+N")
其中
MenuNew()
如下所示:

def MenuNew(self):
print('clicked on new')
fileToOpen = QtWidgets.QFileDialog.getOpenFileName(self)
print(fileToOpen)
if(fileToOpen[0] is not ''):
    print('Change doc')
    self.clearObjects()
    self.setWindowTitle("OpenTester - " + fileToOpen[0])
    #self.convertDocx(fileToOpen[0])
    #self.parse(fileToOpen[0])
    self.displayQuestion(self.test[0],1)
为方便起见,以下是我的完整代码:

# -*- coding: utf-8 -*-
# imports for gui
import sys
import os
from PyQt5 import QtCore, QtWidgets, uic, QtGui

#from testevalutils import gui
# imports for parser
import docx2txt

import Question


# Path to the directory containing this .py file (same directory as .ui file)
THIS_DIR = os.path.abspath(os.path.dirname(__file__))


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        # Calls the QDialog __init__ method with the given parent
        super().__init__(parent)

        # Load the ui file (created by Qt Designer)
        ui_path = os.path.abspath(os.path.join(THIS_DIR, 'MainWindow.ui'))
        uic.loadUi(ui_path, self)

        # initialize test variables
        self.test = []
        self.total_questions = 0
        self.currentQuestion = 0
        self.displayedQuestion = None

        # elements
        self.checkBoxFlag.setText("QUESTION NUM / 999")
        self.textBrowserQuestion.setText("")

        # menu bar
        self.actionNew.triggered.connect(self.MenuNew)
        self.actionNew.setShortcut("Ctrl+N")

    # This decorator (@QtCore.Slot) makes it so this method is automatically
    # connected to the "clicked" signal of the "pushButton_Add" widget by
    # using the naming convention "on_<ObjectName>_<SignalName>"
    @QtCore.Slot()
    def on_actionNew_clicked(self):
        print('Menu>New clicked')

    @QtCore.Slot()
    def on_pushButtonSolution_clicked(self):
        print('Total Solutions to Display {}'.format(self.total_questions))

    @QtCore.Slot()
    def on_pushButtonNext_clicked(self):
        print('Next pushed')
        self.saveState()

        # if not at the last question
        if (self.currentQuestion is self.total_questions):
            print("Finished!")
        else:
            self.currentQuestion = self.currentQuestion + 1
            self.displayQuestion(self.test[self.currentQuestion],1)

    @QtCore.Slot()
    def on_pushButtonBack_clicked(self):
        print('Back pushed')
        self.saveState()
        # go to next question in test array
        self.currentQuestion = self.currentQuestion - 1
        self.displayQuestion(self.test[self.currentQuestion],1)

    # Saves any user changes with check box selections
    # usually called when next or back button is pushed
    def saveState(self):
        checkBoxState = self.checkBoxFlag.isChecked()
        answers = []
        answer1State = self.checkBoxAnswer1.isChecked()
        answers.append(answer1State)
        answer2State = self.checkBoxAnswer2.isChecked()
        answers.append(answer2State)
        answer3State = self.checkBoxAnswer3.isChecked()
        answers.append(answer3State)
        answer4State = self.checkBoxAnswer4.isChecked()
        answers.append(answer4State)
        self.displayedQuestion.SaveState(checkBoxState, answers)
        print('The answer is set to {} {} {} {}'.format(answer1State,answer2State,answer3State,answer4State))

    def disableButton(self, button):
        button.setEnabled(False)

    ### Helper methods ###
    def displayQuestion(self, Question, Number):
        # display question from object we've parsed
        # Add one due to index 0
        num = self.currentQuestion + 1
        self.checkBoxFlag.setText("Question {} of {}".format(num, len(self.test)))
        self.textBrowserQuestion.setText(Question.question)
        self.checkBoxAnswer1.setText(Question.AnswerSetAt(0))
        self.checkBoxAnswer2.setText(Question.AnswerSetAt(1))
        self.checkBoxAnswer3.setText(Question.AnswerSetAt(2))
        self.checkBoxAnswer4.setText(Question.AnswerSetAt(3))

        # load user changes
        self.checkBoxFlag.setChecked(Question.IsFlagged())
        self.checkBoxAnswer1.setChecked(Question.LoadAnswer(0))
        self.checkBoxAnswer2.setChecked(Question.LoadAnswer(1))
        self.checkBoxAnswer3.setChecked(Question.LoadAnswer(2))
        self.checkBoxAnswer4.setChecked(Question.LoadAnswer(3))

        #if first question disable next button
        if(num is 1):
            self.pushButtonBack.setEnabled(False)
        elif (num is self.total_questions - 1):
            self.pushButtonNext.setText("Finish")
        else:
            self.pushButtonBack.setEnabled(True)
            self.pushButtonNext.setText("Next")
        self.displayedQuestion = self.test[self.currentQuestion]
        None

    # Create a txt file "_processed" to read from
    def convertDocx(self, filename):
        rawtext = docx2txt.process(filename + '.docx')
        f = open(filename + '_processed.txt', 'w')
        f.write(rawtext)
        f.close()

    def incrementQuestion(self):
        self.total_questions = self.total_questions + 1

    def addToTest(self, Question):
        self.test.append(Question)

    def clearObjects(self):
        self.test = []
        self.total_questions = 0
        self.currentQuestion = 0
        self.displayedQuestion = 1

    def MenuNew(self):
        print('clicked on new')
        fileToOpen = QtWidgets.QFileDialog.getOpenFileName(self)
        print(fileToOpen)
        if(fileToOpen[0] is not ''):
            print('Change doc')
            self.clearObjects()
            self.setWindowTitle("OpenTester - " + fileToOpen[0])
            #self.convertDocx(fileToOpen[0])
            #self.parse(fileToOpen[0])
            self.displayQuestion(self.test[0],1)

    # Parse from the txt file
    def parse(self, filename):
        question_block = False
        answer_block = False
        explain_block = False
        with open(filename + '_processed.txt') as openfileobject:
            # set our variable for the question
            q_number = None
            q_question = ""
            q_options = []
            q_answer = None
            q_explain = ""
            for line in openfileobject:
                # line.split('\n')
                # print(line)
                # if only a new line then skip it
                if(line == "\n"):
                    continue
                if (not question_block and "QUESTION" in line):
                    question_block = True
                    q_number = line
                    self.total_questions = self.total_questions + 1
                    # skip to next line to check for its properties
                    continue
                # if found next qustion then get each propertiy and add them
                if(question_block):
                    #keep adding lines until we reach the end
                    if("?") in line:
                        question_block = False
                        answer_block = True
                    q_question = q_question + line
                    continue
                if(answer_block):
                    if("A. " in line or "B. " in line or "C. " in line or "D. " in line):
                        line = line[:-1]
                        q_options.append(line)
                        continue
                    if("Correct Answer:") in line:
                        q_answer = line
                        answer_block = False
                        explain_block = True
                        continue
                if(explain_block):
                    if("Reference" not in line):
                        q_explain = q_explain + line
                        continue
                    else:
                        explain_block = False
                        # Add everything into one question
                        new_question = Question.Question(q_number, q_question, q_options, q_answer, q_explain)
                        self.addToTest(new_question)
                        # Reset our question
                        q_number = None
                        q_question = ""
                        q_options = []
                        q_answer = None
                        q_explain = ""


if __name__ == '__main__':
    """Main function that tests the dialog."""
    app = QtWidgets.QApplication.instance()
    if not app:
        app = QtWidgets.QApplication([])
    # This ensures errors are reported from GUI callbacks.
    # Otherwise it would
#    gui.handle_unhandled()

    filedocx = 'comptia_practice_3-21-2018'

    # initialize our window along with the test components already
    w = MainWindow()
    w.show()
    w.setWindowTitle("OpenTester - " + filedocx + ".docx")


    w.convertDocx(filedocx)
    w.parse(filedocx)
    # load first question object
    w.displayQuestion(w.test[w.currentQuestion],1)

    # execute app
    app.exec_()
#-*-编码:utf-8-*-
#用于gui的导入
导入系统
导入操作系统
从PyQt5导入QtCore、QtWidgets、uic、QtGui
#从testevalutils导入gui
#为解析器导入
导入docx2txt
进口问题
#包含此.py文件的目录的路径(与.ui文件的目录相同)
THIS_DIR=os.path.abspath(os.path.dirname(u文件_u))
类MainWindow(QtWidgets.QMainWindow):
def uuu init uuu(self,parent=None):
#使用给定的父级调用QDialog\uuuu init\uuuu方法
super()。\uuuu init\uuuu(父级)
#加载ui文件(由Qt设计器创建)
ui\u path=os.path.abspath(os.path.join(这个目录'MainWindow.ui'))
uic.loadUi(ui\u路径,self)
#初始化测试变量
self.test=[]
self.total_问题=0
self.currentQuestion=0
self.displayedQuestion=None
#元素
self.checkBoxFlag.setText(“问题编号/999”)
self.textBrowserQuestion.setText(“”)
#菜单栏
self.actionNew.triggered.connect(self.MenuNew)
self.actionNew.setShortcut(“Ctrl+N”)
#此装饰符(@QtCore.Slot)使此方法自动
#通过以下方式连接到“按钮添加”小部件的“点击”信号:
#使用命名约定“on_uu;”
@QtCore.Slot()
已单击操作新建时的def(自我):
打印('菜单>新单击')
@QtCore.Slot()
单击按钮解决方案时的def(自身):
打印('totalsolutionstodisplay{}'。格式(self.Total_问题))
@QtCore.Slot()
按下按钮上的def单击下一个按钮(自身):
打印('下一次推送')
self.saveState()
#如果不是在最后一个问题上
如果(self.currentQuestion为self.total_问题):
打印(“完成!”)
其他:
self.currentQuestion=self.currentQuestion+1
self.displayQuestion(self.test[self.currentQuestion],1)
@QtCore.Slot()
按按钮后退时的def(自身):
打印('后推')
self.saveState()
#转到测试数组中的下一个问题
self.currentQuestion=self.currentQuestion-1
self.displayQuestion(self.test[self.currentQuestion],1)
#使用复选框选择保存任何用户更改
#通常在按下下一步或后退按钮时调用
def保存状态(自身):
checkBoxState=self.checkBoxFlag.isChecked()
答案=[]
answer1State=self.checkBoxAnswer1.isChecked()
答案。附加(答案1状态)
answer2State=self.checkBoxAnswer2.isChecked()
答案。附加(答案2状态)
answer3State=self.checkBoxAnswer3.isChecked()
答案。附加(答案3状态)
answer4State=self.checkBoxAnswer4.isChecked()
答案。附加(answer4State)
self.displayedQuestion.SaveState(复选框状态,答案)
打印('答案设置为{}{}{}'。格式(answer1State、answer2State、answer3State、answer4State))
def禁用按钮(自身,按钮):
按钮。设置已启用(错误)
###辅助方法###
def显示问题(自我、问题、编号):
#显示我们解析的对象的问题
#由于索引0,请添加一个
num=self.currentQuestion+1
self.checkBoxFlag.setText(“问题{}的{}”.format(num,len(self.test)))
self.textBrowserQuestion.setText(Question.Question)
self.checkBoxAnswer1.setText(问题.AnswerSetAt(0))
self.checkBoxAnswer2.setText(问题.答案设置在(1))
self.checkBoxAnswer3.setText(问题.答案设置在(2))
self.checkBoxAnswer4.setText(问题.答案设置在(3))
#加载用户更改
self.checkBoxFlag.setChecked(Question.IsFlagged())
self.checkBoxAnswer1.setChecked(问题.加载答案(0))
self.checkBoxAnswer2.setChecked(问题.加载答案(1))
self.checkBoxAnswer3.setChecked(问题.加载答案(2))
self.checkBoxAnswer4.setChecked(问题.加载答案(3))
#如果出现第一个问题,请禁用“下一步”按钮
如果(num为1):
self.pushButtonBack.setEnabled(False)
elif(num是self.total_问题-1):
self.pushButtonNext.setText(“完成”)
其他:
self.pushButtonBack.setEnabled(真)
self.pushButtonNext.setText(“下一步”)
self.displayedQuestion=self.test[self.currentQuestion]
没有一个
#创建一个txt文件“\u processed”以从中读取
def convertDocx(自身,文件名):
rawtext=docx2txt.process(文件名+'.docx')
f=打开(文件名+'\u processed.txt',w')
f、 书写(原始文本)
f、 关闭()
def增量问题(自我):
self.total_问题=self.total_问题+1
def addToTest(自我,问题):
self.test.append(问题)
def clearObjects(自):
self.test=[]
self.total_问题=0
self.currentQuestion=0
self.displayedQuestion=1
def菜单新建(自):
打印('单击新建')
fileToOpen=QtWidgets.QFileDialog.getOpenFileName(self)
打印(文件打开)
如果(fileToOpen[0]不是“”):
打印('变更单')
self.clearObjects()
self.setWindowTitle(“OpenTester-”+fileToOpen[0])
#self.convertDocx(fileToOpen[0])
#self.parse(fileToOpen[0])
self.displayQuestion(self.test[0],1)
#解析