案例3
# -*- coding = utf-8 -*- # @Time : 2022/9/6 11:23 # @Author : Arthur # @FileName : 信号与槽之综合练习.py # @Software : Pycharm import sys import time from PyQt5.QtCore import pyqtSignal, Qt from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QScrollArea, QHBoxLayout class my_window(QWidget): # 声明一个信号 只能放在函数外面 my_signal = pyqtSignal(str) def __init__(self): super(my_window, self).__init__() self.init_ui() self.msg_history = list() def init_ui(self): self.resize(600, 200) # 创建一个整体布局器 container = QVBoxLayout() # 用来显示监测到的漏洞的信息 self.msg = QLabel('') self.msg.resize(500, 15) self.msg.setWordWrap(True) # 自动换行 self.msg.setAlignment(Qt.AlignTop) # 靠上 # 创建一个滚动对象 scroll = QScrollArea() scroll.setWidget(self.msg) # 创建垂直布局器,用来添加自动滚动条 v_layout = QVBoxLayout() v_layout.addWidget(scroll) # 创建水平布局器 h_layout = QHBoxLayout() # 创建一个按钮 btn = QPushButton('开始监测', self) # 绑定按钮的点击,点击按钮开始检测 btn.clicked.connect(self.check) h_layout.addStretch() # 伸缩器 h_layout.addWidget(btn) # 按钮在两个伸缩器之间居中 h_layout.addStretch() # 伸缩器 # 操作将要显示的控件以及子布局器添加到container container.addLayout(v_layout) container.addLayout(h_layout) # 设置布局器 self.setLayout(container) # 绑定信号和槽 self.my_signal.connect(self.my_slot) def my_slot(self, msg): # 更新内容 print(msg) self.msg_history.append(msg) self.msg.setText('<br/>'.join(self.msg_history)) self.msg.resize(500, self.msg.frameSize().height() + 15) self.msg.repaint() # 更新内容,如果不更新坑你没有显示新内容 def check(self): for i, ip in enumerate(['192.168.1.%d' % x for x in range(1, 255)]): msg = '模拟,正在检查 %s 上的漏洞' % ip if i % 5 == 0: # emit 表示发射信号 对象.信号.发射(参数) self.my_signal.emit(msg + '[发现漏洞]') time.sleep(0.01) if __name__ == '__main__': app = QApplication(sys.argv) w = my_window() w.show() app.exec_()
原创文章,作者:朋远方,如若转载,请注明出处:https://caovan.com/pyqt5changyongcaozuozhixinhaoyucao/.html