簡體   English   中英

如何將信號對話框連接到插槽 PyQt5

[英]how to connect the dialog of signal to the slots PyQt5

我正在研究 PyQt5 庫,我找到了一本書(使用 Python 和 Qt 進行快速 GUI 編程)。 但書中的代碼是用 Python 2 和 PyQt4 編寫的。 我正在使用 Python 3 和 PyQt5。 這段代碼來自這本書,我更新了它以適應 Python 3。但是我在運行時仍然有問題。

import re
import PyQt5, sys

from PyQt5.QtCore import *

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import ui_findandreplacedlg



MAC = "qt_mac_set_native_menubar" in dir()


class FindAndReplaceDlg(QDialog, ui_findandreplacedlg.Ui_FindAndReplaceDlg):
    def __init__(self,text,parent = None):
        super(FindAndReplaceDlg,self).__init__(parent)
        self.__text = str(text)
        self.__index = 0
        self.setupUi(self)
        if not MAC:
              self.findButton.setFocusPolicy(Qt.NoFocus)
              self.replaceButton.setFocusPolicy(Qt.NoFocus)
              self.replaceAllButton.setFocusPolicy(Qt.NoFocus)
              self.closeButton.setFocusPolicy(Qt.NoFocus)
        self.updateUi()

    @pyqtSlot("QString")
    def on_findLineEdit_textEdited(self, text):
        self.__index =0
        self.updateUi()

    def updateUi(self):

        enable = not self.findLineEdit.text().isEmpty()
        self.findButton.setEnabled(enable)
        self.replaceButton.setEnabled(enable)
        self.replaceAllButton.setEnabled(enable)

    def text(self):
        return self.__text

    @pyqtSlot()
    def on_findButton_clicked(self):
        regex = self.makeRegex()
        match = regex.search(self.__text,self.__index)
        if match is not None:
            self.__index = match.end()
            self.emit(SIGNSL("found"), match.start())
        else:
            self.emit(SIGNAL("not found"))

    def makeRegex(self):
        findText = str(self.on_findLineEdit.text())
        if str(self.syntaxComboBox.currentText()) == "Literal":
            findText = re.escape(findText)
        flags = re.MULTILINE|re.DOTALL|re.UNICODE
        if not self.caseCheckBox.isChecked():
            flags |=re.IGNORECASE
        if self.wholeCheckBox.isChecked():
            findText = r"\b%s\b" % findText 
        return re.compile(findText, flags)

    @pyqtSlot()
    def on_replaceButton_clicked(self):
        regex = self.makeRegex()
        self.__text = regex.sub(str(self.replaceLineEdit.text()), self.__text,1)

    @pyqtSlot()
    def on_replaceAllButton_clicked(self):
        regex = self.makeRegex()
        self.__text = regex.sub(str(self.replaceLineEdit.text()),self.__text)



if __name__ == "__main__":

    text = """US experience shows that, unlike traditional patents,
software patents do not encourage innovation and R&D, quite the contrary. In particular they hurt small and medium-sized
enterprises and generally  newcomers in the market. They will just weaken the market and increase spending on patents and
litigation, at the expense of technological innovation and research. Especially dangerous are attempts to abuse the patent system by preventing 
interoperability as a means of avoiding competition with technological ability. --- Extract quoted from Linus Torvalds and Alan Cox's letter
to the President of the European Parliament
http://www.effi.org/patentit/patents_torvalds_cox.html"""

    def found(where):
        print(("Found at %d" % where))

    def nomore():
        print ("No more found")

    app = QApplication(sys.argv)
    form = FindAndReplaceDlg(text)

    form.connect(form, SIGNAL("found"),nomore)

    form.connect(form, SIGNAL("not found"),found)

    form.show()
    app.exec_()
    print((form.text()))

這一行的第一個錯誤

def updateUi(self):

    enable = not self.findLineEdit.text().isEmpty()
    ('str' object has no attribute 'isEmpty')

最后的第二個錯誤

 form = FindAndReplaceDlg(text)
 form.connect(form, SIGNAL("found"),nomore)
 form.connect(form, SIGNAL("not found"),found)

('FindAndReplaceDlg' 沒有屬性 'connect')有人可以幫我嗎? 而且,如果您知道任何學習 Qt Desiner 和 PyQt5 的好書,我也會很高興!

在 PyQt4 中,QLineEdit 的 text 方法返回一個 QString,但在 PyQt5 中它返回一個 str 以保持與 python 的兼容性,因此如果要驗證字符串是否為空,則必須使用 python 的傳統方法。 另一方面在 PyQt5 中你必須使用新的連接語法,此外,不再允許動態創建信號,因此你必須將其更改為:

import re
from PyQt5 import QtCore, QtGui, QtWidgets
import ui_findandreplacedlg


MAC = "qt_mac_set_native_menubar" in dir()


class FindAndReplaceDlg(
    QtWidgets.QDialog, ui_findandreplacedlg.Ui_FindAndReplaceDlg
):
    found = QtCore.pyqtSignal(int)
    not_found = QtCore.pyqtSignal()

    def __init__(self, text, parent=None):
        super(FindAndReplaceDlg, self).__init__(parent)
        self.__text = str(text)
        self.__index = 0
        self.setupUi(self)
        if not MAC:
            for btn in (
                self.findButton,
                self.replaceButton,
                self.replaceAllButton,
                self.closeButton,
            ):
                btn.setFocusPolicy(QtCore.Qt.NoFocus)
        self.updateUi()

    @QtCore.pyqtSlot(str)
    def on_findLineEdit_textEdited(self, text):
        self.__index = 0
        self.updateUi()

    def updateUi(self):

        enable = bool(self.findLineEdit.text())
        self.findButton.setEnabled(enable)
        self.replaceButton.setEnabled(enable)
        self.replaceAllButton.setEnabled(enable)

    def text(self):
        return self.__text

    @QtCore.pyqtSlot()
    def on_findButton_clicked(self):
        regex = self.makeRegex()
        match = regex.search(self.__text, self.__index)
        if match is not None:
            self.__index = match.end()
            print(match.start())
            self.found.emit(match.start())
        else:
            self.not_found.emit()

    def makeRegex(self):
        findText = str(self.on_findLineEdit.text())
        if str(self.syntaxComboBox.currentText()) == "Literal":
            findText = re.escape(findText)
        flags = re.MULTILINE | re.DOTALL | re.UNICODE
        if not self.caseCheckBox.isChecked():
            flags |= re.IGNORECASE
        if self.wholeCheckBox.isChecked():
            findText = r"\b%s\b" % findText
        return re.compile(findText, flags)

    @QtCore.pyqtSlot()
    def on_replaceButton_clicked(self):
        regex = self.makeRegex()
        self.__text = regex.sub(
            str(self.replaceLineEdit.text()), self.__text, 1
        )

    @QtCore.pyqtSlot()
    def on_replaceAllButton_clicked(self):
        regex = self.makeRegex()
        self.__text = regex.sub(str(self.replaceLineEdit.text()), self.__text)


if __name__ == "__main__":
    import sys

    text = """US experience shows that, unlike traditional patents,
software patents do not encourage innovation and R&D, quite the contrary. In particular they hurt small and medium-sized
enterprises and generally  newcomers in the market. They will just weaken the market and increase spending on patents and
litigation, at the expense of technological innovation and research. Especially dangerous are attempts to abuse the patent system by preventing 
interoperability as a means of avoiding competition with technological ability. --- Extract quoted from Linus Torvalds and Alan Cox's letter
to the President of the European Parliament
http://www.effi.org/patentit/patents_torvalds_cox.html"""

    def found(where):
        print(("Found at %d" % where))

    def nomore():
        print("No more found")

    app = QtWidgets.QApplication(sys.argv)
    form = FindAndReplaceDlg(text)

    form.found.connect(nomore)

    form.not_found.connect(found)

    form.show()
    app.exec_()
    print((form.text()))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM