PyQt在处理偶数循环时避免陷入无限循环

2024-05-19 18:41:57 发布

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

在PyQt中,每次剪贴板内容发生变化时,我都会尝试获取它的内容,执行一些操作以将输出计算为文本并将其再次放入剪贴板。你知道吗

问题似乎是,当我在“clipboard content changed”事件处理函数中更改剪贴板的内容时,会触发并反复调用该函数。你知道吗

这是我正在使用的代码:

import sys
from PyQt5.Qt import QApplication, QClipboard
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QPlainTextEdit
from PyQt5.QtCore import QSize

class ExampleWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setMinimumSize(QSize(440, 240))
        self.setWindowTitle("PyQt5 Clipboard example")

        # Add text field
        self.b = QPlainTextEdit(self)
        self.b.insertPlainText("Use your mouse to copy text to the clipboard.\nText can be copied from any application.\n")
        self.b.move(10,10)
        self.b.resize(400,200)

        # clipboard
        self.cb = QApplication.clipboard()
        self.cb_changed_handler = self.cb.dataChanged.connect(self.clipboardChanged)

    def clipboardChanged(self):
        text = self.cb.text()
        print(text)
        self.b.insertPlainText(text + '\n')
        self.cb.clear(mode=self.cb.Clipboard)
        self.cb.setText("this is a text", mode=self.cb.Clipboard) # this creates an infinite loop!!    

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

我还尝试了以下clipboardChanged函数,但没有成功,python崩溃了:

def clipboardChanged(self):
    text = self.cb.text()
    print(text)
    self.b.insertPlainText(text + '\n')
    # This does not work, python crashes!!
    # let's disable the event listener, do what we should and restore the event
    self.cb.dataChanged().disconnect()
    self.cb.clear(mode=self.cb.Clipboard)
    self.cb.setText("this is a text", mode=self.cb.Clipboard)
    self.cb_changed_handler = self.cb.dataChanged.connect(self.clipboardChanged)

我用的是Windows。你知道吗

执行此操作后

from PyQt5.Qt import PYQT_VERSION_STR
print("PyQt version:", PYQT_VERSION_STR)

我明白了

PyQt version: 5.9.2

Tags: 函数textfromimportself内容modepyqt5
1条回答
网友
1楼 · 发布于 2024-05-19 18:41:57

解决方案是防止使用^{}的clipboardChanged方法发出QClipBoard ^{}信号:

def clipboardChanged(self):
    text = self.cb.text()
    print(text)
    self.b.insertPlainText(text + '\n')
    self.cb.blockSignals(True)
    self.cb.clear(mode=self.cb.Clipboard)
    self.cb.setText("this is a text", mode=QClipboard.Clipboard)   
    self.cb.blockSignals(False)

相关问题 更多 >