#python #pyqt5 #qt-designer
Вопрос:
Я пытаюсь разработать настольное приложение в pycharm с помощью Qt Designer. Поэтому из конструктора я извлекаю main_ui.py файл со всем моим интерфейсом
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setWindowModality(QtCore.Qt.ApplicationModal) MainWindow.resize(1404, 792) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) MainWindow.setFocusPolicy(QtCore.Qt.StrongFocus) MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight) MainWindow.setAutoFillBackground(False) MainWindow.setStyleSheet("") MainWindow.setAnimated(False) MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.main_fm = QtWidgets.QFrame(self.centralwidget) self.main_fm.setGeometry(QtCore.QRect(310, -10, 1071, 800)) self.main_fm.setStyleSheet("background-color: "#116466"") self.main_fm.setFrameShape(QtWidgets.QFrame.NoFrame) self.main_fm.setFrameShadow(QtWidgets.QFrame.Plain) self.main_fm.setObjectName("main_fm") self.maintoolbar_fm = QtWidgets.QFrame(self.main_fm) self.maintoolbar_fm.setGeometry(QtCore.QRect(0, 0, 1061, 35)) self.maintoolbar_fm.setLayoutDirection(QtCore.Qt.RightToLeft) self.maintoolbar_fm.setStyleSheet("background-color: "#116466";") self.maintoolbar_fm.setFrameShape(QtWidgets.QFrame.StyledPanel) self.maintoolbar_fm.setFrameShadow(QtWidgets.QFrame.Raised) self.maintoolbar_fm.setObjectName("maintoolbar_fm") self.horizontalLayout = QtWidgets.QHBoxLayout(self.maintoolbar_fm) self.horizontalLayout.setObjectName("horizontalLayout") self.main_exit2_btn = QtWidgets.QPushButton(self.maintoolbar_fm) self.main_exit2_btn.setFocusPolicy(QtCore.Qt.NoFocus) self.main_exit2_btn.setStyleSheet("") self.main_exit2_btn.setText("") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icons/exit.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.main_exit2_btn.setIcon(icon) self.main_exit2_btn.setFlat(True) self.main_exit2_btn.setObjectName("main_exit2_btn") self.horizontalLayout.addWidget(self.main_exit2_btn) self.minim2_btn = QtWidgets.QPushButton(self.maintoolbar_fm) self.minim2_btn.setFocusPolicy(QtCore.Qt.NoFocus) self.minim2_btn.setStyleSheet("") self.minim2_btn.setText("") self.members_bt.setIcon(icon9) self.members_bt.setIconSize(QtCore.QSize(45, 40)) self.members_bt.setFlat(True) self.members_bt.setObjectName("members_bt") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "ΑΞΙΟΝ ΠΕΙΡΑΙΑ")) self.title_date.setText(_translate("MainWindow", "Todaydate")) self.author_lb.setText(_translate("MainWindow", "David Dan")) self.sum_oplo.setText(_translate("MainWindow", "0")) self.sum_members_lb_4.setText(_translate("MainWindow", "Οπλομαχία:")) self.sum_fencing.setText(_translate("MainWindow", "0")) self.sum_members_lb_3.setText(_translate("MainWindow", "Ξιφασκια:")) self.sum_tkd.setText(_translate("MainWindow", "0")) self.sum_members_lb_2.setText(_translate("MainWindow", "Taekwon-Do:")) self.sum_members.setText(_translate("MainWindow", "0")) self.sum_members_lb.setText(_translate("MainWindow", "Σύνολο:")) self.sum_oplo_pre.setText(_translate("MainWindow", "0")) self.oplo_pres_lb.setText(_translate("MainWindow", "Οπλομαχία:")) self.sum_fencing_pre.setText(_translate("MainWindow", "0")) self.fencing_pres_lb.setText(_translate("MainWindow", "Ξιφασκια:")) self.sum_tkd_pre.setText(_translate("MainWindow", "0")) self.tae_pre_lb.setText(_translate("MainWindow", "Taekwon-Do:")) self.sum_pres.setText(_translate("MainWindow", "0")) self.sum_pres_lb.setText(_translate("MainWindow", "Σύνολο:")) self.title_members_lb.setText(_translate("MainWindow", "Μέλη")) self.title_present_lb.setText(_translate("MainWindow", "Παρουσίες Σήμερα")) self.title_eco_lb.setText(_translate("MainWindow", "Οικονομικά")) self.expe_eco_lb.setText(_translate("MainWindow", "0")) self.exp_eco_title_lb.setText(_translate("MainWindow", "Έξοδα:")) self.oplo_eco_lb.setText(_translate("MainWindow", "0")) self.oplo_eco_title_lb.setText(_translate("MainWindow", "Οπλομαχία:"))
Также у меня есть main.py файл, в котором я запускаю весь свой код. В этом файле я извлекаю данные из своего календаря Google и хочу динамически создавать QLabels для каждого события.
вот мой main.py в качестве примера:
import datetime from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton from PyQt5.QtCore import Qt, QRect, QPropertyAnimation, QParallelAnimationGroup, QDate from PyQt5 import QtGui, QtWidgets from login_main import Ui_MainWindow import google_calendar import sys import login_query class LoginWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) global buttons_style buttons_style = "QToolTip { background-color: black } QPushButton { border-left: 5px solid #88b1b2; border-radius: 13px 0px 0px 13px; background-color: #116466} " global widgets widgets = self.ui global start_pos_x start_pos_x = 150 global start_pro_y start_pro_y = 150 self.baseHeight = 369 self.extendedHeight = 400 self.rect = QRect(start_pos_x, start_pro_y, 320, self.baseHeight) self.setGeometry(self.rect) # this will hide the title bar self.setWindowFlag(Qt.FramelessWindowHint) widgets.toggle_bt.clicked.connect(self.buttonClick) widgets.home_bt.clicked.connect(self.buttonClick) widgets.taek_bt.clicked.connect(self.buttonClick) widgets.fencing_bt.clicked.connect(self.buttonClick) widgets.oplo_bt.clicked.connect(self.buttonClick) widgets.eco_bt.clicked.connect(self.buttonClick) widgets.prese_bt.clicked.connect(self.buttonClick) widgets.members_bt.clicked.connect(self.buttonClick) #################################################### widgets.login_btn.clicked.connect(self.pressed) #################################################### widgets.main_exit_btn.clicked.connect(self.close) widgets.minim_btn.clicked.connect(self.showMinimized) #################################################### widgets.main_exit2_btn.clicked.connect(self.close) widgets.minim2_btn.clicked.connect(self.showMinimized) #################################################### self.installEventFilter(self) self.displayTime() widgets.toolBar_fm.hide() self.show() def displayTime(self): now = QDate.currentDate() widgets.title_date.setText(now.toString(Qt.DefaultLocaleLongDate)) def buttonClick(self): # GET BUTTON CLICKED btn = self.sender() btnName = btn.objectName() ################# def pressed(self): if (widgets.user_tb.text() == "" or widgets.user_tb.text() == "Username") and ( widgets.pass_tb.text() == "" or widgets.pass_tb.text() == "Password"): widgets.info_lb.setText("No username and password") print("No username and password inserted") #################################### def refresh_calendar(self): calendar_list = google_calendar.calendar_data.main(self) if calendar_list[0] == "empty": print("No Calendar Events") widgets.calendar_error_lb.setText("No Calendar Events") else: print("Calendar List:") print(calendar_list) print("Each Item:") for item in calendar_list: dayWeek = datetime.datetime.strptime(item[0], '%d-%m-%Y').strftime('%A') print(item[0], dayWeek, item[1], item[2], item[3]) HERE I WANT TO CREATE A LABEL FOR EACH ELEMENT IN calendar_list according the week day in my main window if dayWeek == 'Monday': pass elif dayWeek == 'Tuesday': pass elif dayWeek == 'Wednesday': pass elif dayWeek == 'Thursday': pass elif dayWeek == 'Friday': pass #friday_fm elif dayWeek == 'Saturday': pass elif dayWeek == 'Saturday': pass print("##################### END of Calendar event List ##############################") def refresh_stats(self): # MEMBERS STATS members_array = login_query.connection.login_members_stats(self, widgets.user_tb.text(), widgets.pass_tb.text()) widgets.sum_members.setText(str(members_array[0])) widgets.sum_tkd.setText(str(members_array[1])) widgets.sum_fencing.setText(str(members_array[2])) widgets.sum_oplo.setText(str(members_array[3])) def keyPressEvent(self, qKeyEvent): # αναγνωριζει τα enter και καλει την συναρτηση οταν πατιεται το login button print(qKeyEvent.key()) if qKeyEvent.key() == Qt.Key_Return or qKeyEvent.key() == Qt.Key_Enter: self.pressed() print('Enter pressed') def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.offset = event.pos() else: super().mousePressEvent(event) def mouseMoveEvent(self, event): if self.offset is not None and event.buttons() == Qt.LeftButton: self.move(self.pos() event.pos() - self.offset) else: super().mouseMoveEvent(event) def mouseReleaseEvent(self, event): self.offset = None super().mouseReleaseEvent(event) def resetStyle(self, btnName): for w in self.ui.toolBar_fm.findChildren(QPushButton): if w.objectName() != btnName: w.setStyleSheet("") print("resetStyle") # Create the application object if __name__ == "__main__": app = QApplication(sys.argv) window = LoginWindow() sys.exit(app.exec_())
Итак, вопрос в том, как создавать/добавлять метки в главном окне(и внутри Qframe) без добавления кода в main_ui.py.
thnx заранее.
Комментарии:
1. Создайте макет и добавьте в него виджеты, затем включите макет
self.ui.main_fm
.
Ответ №1:
Thnx много @ekhumoro макет-это ответ….слишком простой.
layout1 = QGridLayout() item1 = QLabel(item[3]) item2 = QLabel(item[1]) layout1.addWidget(item1) layout1.addWidget(item2) widgets.friday_fm.setLayout(layout1)
Комментарии:
1. Однако я не могу сортировать виджеты в макете, потому что при использовании вертикального, горизонтального, сеточного или формового макета они сортируются автоматически. Я думал, что смогу использовать распорки, но это чрезвычайно сложно сделать динамически. ЕСТЬ КАКИЕ-НИБУДЬ ИДЕИ???