来自窗口的pyqt信号未更改主窗口小部件

时间:2020-09-29 10:10:29

标签: python-3.x pyqt5 qt-designer

我可以使用信号在两个窗口之间传递值, 当我从另一个窗口按下按钮时,我想更改纯文本。 但是insertPlainText甚至text.show()都不起作用

我尝试过将信号发送到Mainwindow的init部分, 尝试过更新,重新粉刷,但是它们都不起作用。

感谢您的帮助,谢谢!


将SearchWindow类中的search_send方法转换为MainWindow方法test _

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.tag_box.hide()

    def test_(self, i): # -------problem here------------------
        print(i)  // <- value here were right
        self.ui.tag_box.insertPlainText(i)  # -------Plain Text does not change-------
        self.ui.tag_box.show()# -------Plain Text does not show either--------------


class SearchWindow(QtWidgets.QMainWindow):
    
    signal=pyqtSignal(str)

    def __init__(self, endpoint=None, user=None, password=None, points_link=None):
        super(SearchWindow, self).__init__()
        self.ui = Ui_Search()
        self.ui.setupUi(self)
        self.ui.pushButton_2.clicked.connect(self.search_send)

    def search_send(self): # -------problem here------------------
        tag_list = [tag1,tag2, tag3]
        otherClass = MainWindow()
        self.signal.connect(otherClass.test_)
        for k in tag_list:
            self.signal.emit(k)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

由于我们不清楚Ui_Dialog包含什么内容,因此我无法确切地说出问题所在,但可以向您展示应如何使用 Signal

这是Signal的示例,该文本正在将文本传输到Slot。名称在 PyQt5 中可能有所不同-相应更改。

from PySide2.QtWidgets import QWidget, QApplication, QPlainTextEdit, QTextEdit, QVBoxLayout
from PySide2.QtCore import Signal, Slot
import sys


class MainWindow(QWidget):
    sig = Signal(str)

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Main")
        self.layout = QVBoxLayout()
        self.text = QTextEdit()
        self.layout.addWidget(self.text)
        self.setLayout(self.layout)

        self.text.textChanged.connect(self.onChange)

    def onChange(self):
        self.sig.emit(self.text.toPlainText())


class SubWindow(QWidget):

    def __init__(self, connect_target: MainWindow):
        super(SubWindow, self).__init__()
        self.setWindowTitle("Sub")
        self.layout = QVBoxLayout()
        self.text = QPlainTextEdit()
        self.layout.addWidget(self.text)
        self.setLayout(self.layout)

        connect_target.sig.connect(self.onSignal)

    @Slot(str)
    def onSignal(self, text):
        self.text.insertPlainText(text + '\r\n')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    window_sub = SubWindow(window)
    window_sub.show()
    sys.exit(app.exec_())

Main 中的所有内容都会根据需要插入 QPlainTextEdit

enter image description here