pyqt5 子窗口的创建,以及主窗口和子窗口的通信
使用designer 画好ui,注意选择dialog对话框
然后将ui文件转换成py
目标和源文件换成你自己的
pyuic5 -o qt_hgbp.py htbp_autotest.ui
主窗口调用子窗口
方法一:常规调用,
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog
## 引入主窗口ui转py文件
from dust.mainWindow import *
## 引入子串口ui转py文件
from dust.childWindow import *
if __name__ == '__main__':
app = QApplication(sys.argv)
#实例化主窗口
main = QMainWindow()
main_ui = Ui_MainWindow()
main_ui.setupUi(main )
#实例化子窗口
child = QDialog() ##基于dailog对象
child_ui = Ui_Dialog()
child_ui.setupUi(child)
#按钮绑定事件
btn = main_ui.pushButton
btn.clicked.connect( child.show )
#显示
main.show()
sys.exit(app.exec_())
以上的子窗口存在一个问题,那就是子串口无法自定义隐藏窗口
以下是优化代码
···
## 继承dialog类 ,从ui转换来的子对话框
class SubDialog(QtWidgets.QDialog,Ui_Dialog): ## 参数传进去Ui_Dialog
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton_3.clicked.connect(self.close)
self.pushButton_2.clicked.connect(self.showMinimized)
self.initUI()
def initUI(self):
self.setWindowTitle('Sub Dialog')
self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #隐藏边框
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint) # 隐藏边框
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowMinimizeButtonHint) # 隐藏最小化按钮
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowMaximizeButtonHint) # 隐藏最大化按钮
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowCloseButtonHint) # 隐藏关闭按钮
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.m_flag = True
self.m_Position = event.globalPos() - self.pos()
event.accept()
self.setCursor(QCursor(Qt.OpenHandCursor)) #按住改变鼠标
def mouseMoveEvent(self, QMouseEvent):
if Qt.LeftButton and self.m_flag:
self.move(QMouseEvent.globalPos() - self.m_Position)
QMouseEvent.accept()
def mouseReleaseEvent(self, QMouseEvent):
self.m_flag = False
self.setCursor(QCursor(Qt.ArrowCursor)) #松开鼠标变箭头
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
form= QtWidgets.QMainWindow()
# form.setWindowTitle("hgbp_auto")
# form.setWindowIcon(QtGui.QIcon("res/bikini60s_weather.svg")) ##设置图标 相对路径不需要加../
w= Ui_MainWindow()
w.setupUi(form)
## 实例化子窗口
## 按钮绑定子窗口
w.actioncanshu.triggered.connect(child_ui.show)
# form.setWindowFlags(QtCore.Qt.FramelessWindowHint) #隐藏边框
form.show()
sys.exit(app.exec_())