Нужно сделать адаптацию .ui файла под SubWindow в QWidget для открытия второго окна.
favourite_ui.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SubWindow(object):
def setupUi(self, SubWindow):
SubWindow.setObjectName("SubWindow")
SubWindow.resize(303, 350)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("res/icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
SubWindow.setWindowIcon(icon)
self.centralwidget = QtWidgets.QWidget(SubWindow)
self.centralwidget.setObjectName("centralwidget")
self.favConnBtn = QtWidgets.QPushButton(self.centralwidget)
self.favConnBtn.setGeometry(QtCore.QRect(10, 250, 131, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.favConnBtn.setFont(font)
self.favConnBtn.setObjectName("favConnBtn")
self.favExitBtn = QtWidgets.QPushButton(self.centralwidget)
self.favExitBtn.setGeometry(QtCore.QRect(160, 250, 131, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.favExitBtn.setFont(font)
self.favExitBtn.setObjectName("favExitBtn")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(10, 50, 281, 192))
self.listWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.listWidget.setObjectName("listWidget")
self.favAddBtn = QtWidgets.QPushButton(self.centralwidget)
self.favAddBtn.setGeometry(QtCore.QRect(10, 290, 131, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.favAddBtn.setFont(font)
self.favAddBtn.setObjectName("favAddBtn")
self.favDelBtn = QtWidgets.QPushButton(self.centralwidget)
self.favDelBtn.setGeometry(QtCore.QRect(160, 290, 131, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.favDelBtn.setFont(font)
self.favDelBtn.setObjectName("favDelBtn")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(30, 0, 241, 31))
font = QtGui.QFont()
font.setPointSize(18)
self.label.setFont(font)
self.label.setObjectName("label")
SubWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(SubWindow)
self.statusbar.setObjectName("statusbar")
SubWindow.setStatusBar(self.statusbar)
self.retranslateUi(SubWindow)
QtCore.QMetaObject.connectSlotsByName(SubWindow)
def retranslateUi(self, SubWindow):
_translate = QtCore.QCoreApplication.translate
SubWindow.setWindowTitle(_translate("SubWindow", "Serewasfera\'s Chat - Закладки"))
self.favConnBtn.setText(_translate("SubWindow", "Соединение"))
self.favExitBtn.setText(_translate("SubWindow", "Выход"))
self.favAddBtn.setText(_translate("SubWindow", "Добавить..."))
self.favDelBtn.setText(_translate("SubWindow", "Удалить"))
self.label.setText(_translate("SubWindow", "Сервера в закладках:"))
main.py
import sys
import chatUI
import favourite_ui
import os
import socket
import random
from threading import Thread
from datetime import datetime
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic
import configparser
config = configparser.ConfigParser()
config.read("config.ini")
separator_token = "<SEP>"
class SubWindow(QWidget): #сюда нужно адаптировать код
def __init__(self):
super().__init__()
class ExampleApp(QtWidgets.QMainWindow, chatUI.Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.connBtn.clicked.connect(self.defConnectBtn)
self.sendBtn.clicked.connect(self.defSendBtn)
self.abtBtn.clicked.connect(self.defAbtBtn)
self.optBtn.clicked.connect(self.defOptBtn)
self.logBtn.clicked.connect(self.defLogBtn)
self.sub_window = SubWindow()
self.favouriteBtn.clicked.connect(self.sub_window.show)
def defLogBtn(self):
os.system("last.log")
def defOptBtn(self):
os.system("config.ini")
def defConnectBtn(self):
IP = self.ipEdit.toPlainText()
PORT = self.textEdit_2.toPlainText()
global s
s = socket.socket()
self.listWidget.addItem(f"[Чат] Соединение с {IP}:{PORT}...")
try:
s.connect((IP, int(PORT)))
except ValueError:
self.listWidget.addItem("[Чат] Порт должен быть числовым значением!")
s.close()
return('break')
except ConnectionRefusedError:
self.listWidget.addItem("[Чат] Сервер не найден! Проверьте введённые IP и порт!")
s.close()
return('break')
except socket.gaierror:
self.listWidget.addItem("[Чат] Сервер не найден! Проверьте введённые IP и порт!")
s.close()
return('break')
except OSError:
self.listWidget.addItem("[Чат] Сервер не найден! Проверьте введённые IP и порт!")
s.close()
return('break')
except OverflowError:
self.listWidget.addItem("[Чат] Проверьте введённые IP и порт!")
s.close()
return('break')
self.listWidget.addItem(f"[Чат] Успешно соединён с {IP}:{PORT}!")
with open('last.log', 'a') as f:
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
f.write(f'\n//{IP}:{PORT} log. Connection time: {date_now}//')
f.close()
def listen_for_messages():
while True:
message = s.recv(1024).decode()
self.listWidget.addItem(message)
with open('last.log', 'a') as f:
f.write(f'\n{message}')
f.close
t = Thread(target=listen_for_messages)
t.daemon = True
t.start()
def defSendBtn(self):
to_send = self.sendEdit.toPlainText()
name = self.nameEdit.toPlainText()
if name == "":
name = "безимянный"
if to_send.lower() == 'q':
pass
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
to_send = f"[{date_now}] {name}{separator_token}{to_send}"
try:
s.send(to_send.encode())
except NameError:
self.listWidget.addItem("[Чат] Вы не подключены к серверу!")
def defAbtBtn(self):
os.system("about.txt")
def main():
app = QtWidgets.QApplication(sys.argv)
window = ExampleApp()
window.show()
app.exec_()
if __name__ == '__main__':
main()
try:
s.close()
except NameError:
pass