I want to call a function that checks words count in a lineEdit whenever I press space key inside the lineEdit. But how can I do that. After executing the python file press 'Start Game' to go to the lineEdit. Thanks!
Here's my code:
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QLineEdit, QPushButton, QTextBrowser, QStackedWidget, QWidget, QLCDNumber, QComboBox
from PyQt5 import uic
import sys
from PyQt5.QtGui import QKeyEvent
from PyQt5.QtCore import QThread, pyqtSignal, Qt
import random
class UI(QMainWindow):
def __init__(self):
super(UI, self).__init__()
# Load the ui file
uic.loadUi("Typing_test_UI.ui", self)
# Define our widgets
self.textBrowser = self.findChild(QTextBrowser, "textBrowser")
self.lineEdit = self.findChild(QLineEdit, "lineEdit")
self.counter = self.findChild(QLCDNumber, "counter")
self.startBtn = self.findChild(QPushButton, "startBtn")
self.timeCombo = self.findChild(QComboBox, "timeCombo")
self.difficultyCombo = self.findChild(QComboBox, "difficultyCombo")
self.stackedWidget = self.findChild(QStackedWidget, "stackedWidget")
self.startPage = self.findChild(QWidget, "startPage")
self.gamePage = self.findChild(QWidget, "gamePage")
self.scorePage = self.findChild(QWidget, "scorePage")
self.highScoreLabel = self.findChild(QLabel, "highScoreLabel")
self.scoreLabel = self.findChild(QLabel, "scoreLabel")
self.retryBtn = self.findChild(QPushButton, "retryBtn")
self.space_count = 0
self.startBtn.clicked.connect(self.start_game)
self.retryBtn.clicked.connect(self.goto_home_page)
# Show the app
self.show()
def start_game(self):
self.stackedWidget.setCurrentWidget(self.gamePage)
self.textBrowser.clear()
with open("Typing_sentences.txt", "r") as f:
all_texts = f.readlines()
lines_of_text = len(all_texts)
self.textBrowser.append(all_texts[random.randint(0, lines_of_text-1)])
def goto_home_page(self):
self.stackedWidget.setCurrentWidget(self.startPage)
app = QApplication(sys.argv)
UIWindow = UI()
app.exec_()
The sentences for a function in my code:
He found himself sitting at his computer, typing whatever came to mind. He was on a website entitled 10 fast fingers. This site tested how fast you were at typing. So he typed. He was currently typing about himself typing, which is odd in a way. He was now describing about how he was typing about himself typing.
The Internet is the global system of interconnected computer networks that uses the Internet protocol suite to communicate between networks and devices. It is a network of networks that consists of private, public, academic, business, and government networks of local to global scope, linked by a broad array of electronic, wireless, and optical networking technologies. The Internet carries a vast range of information resources and services, such as the inter-linked hypertext documents and applications of the World Wide Web (WWW), electronic mail, telephony, and file sharing.
The ui file:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>801</width>
<height>443</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>801</width>
<height>443</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>801</width>
<height>443</height>
</size>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QStackedWidget" name="stackedWidget">
<property name="currentIndex">
<number>2</number>
</property>
<widget class="QWidget" name="startPage">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QWidget" name="widget_3" native="true">
<widget class="QComboBox" name="timeCombo">
<property name="geometry">
<rect>
<x>280</x>
<y>60</y>
<width>201</width>
<height>41</height>
</rect>
</property>
<property name="font">
<font>
<pointsize>11</pointsize>
</font>
</property>
<item>
<property name="text">
<string>1 Minute</string>
</property>
</item>
<item>
<property name="text">
<string>2 Minutes</string>
</property>
</item>
<item>
<property name="text">
<string>5 Minutes</string>
</property>
</item>
<item>
<property name="text">
<string>10 Minutes</string>
</property>
</item>
</widget>
<widget class="QComboBox" name="difficultyCombo">
<property name="geometry">
<rect>
<x>280</x>
<y>130</y>
<width>201</width>
<height>41</height>
</rect>
</property>
<property name="font">
<font>
<pointsize>12</pointsize>
</font>
</property>
<item>
<property name="text">
<string>Easy</string>
</property>
</item>
<item>
<property name="text">
<string>Medium</string>
</property>
</item>
<item>
<property name="text">
<string>Hard</string>
</property>
</item>
</widget>
<widget class="QPushButton" name="startBtn">
<property name="geometry">
<rect>
<x>230</x>
<y>230</y>
<width>301</width>
<height>61</height>
</rect>
</property>
<property name="font">
<font>
<pointsize>16</pointsize>
</font>
</property>
<property name="text">
<string>Start Game</string>
</property>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="gamePage">
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0" alignment="Qt::AlignRight|Qt::AlignTop">
<widget class="QWidget" name="widget_2" native="true">
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item alignment="Qt::AlignRight">
<widget class="QLCDNumber" name="counter">
<property name="minimumSize">
<size>
<width>150</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>150</width>
<height>16777215</height>
</size>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="1" column="0">
<widget class="QWidget" name="widget" native="true">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="2">
<widget class="QTextBrowser" name="textBrowser"/>
</item>
<item row="1" column="0" colspan="2">
<widget class="QLineEdit" name="lineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>45</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>45</height>
</size>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="scorePage">
<widget class="QLabel" name="scoreLabel">
<property name="geometry">
<rect>
<x>240</x>
<y>90</y>
<width>300</width>
<height>71</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>300</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>100</height>
</size>
</property>
<property name="font">
<font>
<pointsize>20</pointsize>
</font>
</property>
<property name="text">
<string>Score: 0</string>
</property>
</widget>
<widget class="QPushButton" name="retryBtn">
<property name="geometry">
<rect>
<x>652</x>
<y>320</y>
<width>121</width>
<height>64</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>64</width>
<height>64</height>
</size>
</property>
<property name="text">
<string>Retry</string>
</property>
<property name="iconSize">
<size>
<width>64</width>
<height>64</height>
</size>
</property>
</widget>
<widget class="QLabel" name="highScoreLabel">
<property name="geometry">
<rect>
<x>291</x>
<y>185</y>
<width>200</width>
<height>18</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>200</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>50</height>
</size>
</property>
<property name="font">
<font>
<pointsize>9</pointsize>
</font>
</property>
<property name="text">
<string>High Score: 0</string>
</property>
</widget>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>801</width>
<height>26</height>
</rect>
</property>
<widget class="QMenu" name="menuPapers">
<property name="title">
<string>Options</string>
</property>
<widget class="QMenu" name="menuTest_papers">
<property name="title">
<string>Test papers</string>
</property>
<addaction name="actionRandom"/>
<addaction name="actionChoose"/>
</widget>
<addaction name="menuTest_papers"/>
<addaction name="actionReset"/>
</widget>
<addaction name="menuPapers"/>
</widget>
<action name="actionRandom">
<property name="text">
<string>Random</string>
</property>
</action>
<action name="actionChoose">
<property name="text">
<string>Choose</string>
</property>
</action>
<action name="actionReset">
<property name="text">
<string>Reset High Score</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>
Here is an example of installing an Event Filter on the QLineEdit as suggested. See the inline comments for details and explanation.
...
class UI(QMainWindow):
def __init__(self):
super(UI, self).__init__()
# Load the ui file
uic.loadUi("Typing_test_UI.ui", self)
# Define our widgets
...
...
self.spaceFilter = SpaceFilter(parent=self) # init filter
self.spaceFilter.spacePressed.connect(self.my_function) # connect to the signal
self.lineEdit.installEventFilter(self.spaceFilter) # install on lineedit
self.space_count = 0
self.startBtn.clicked.connect(self.start_game)
self.retryBtn.clicked.connect(self.goto_home_page)
# Show the app
self.show()
def my_function(self): # custom function that runs when space bar is
for i in range(5): # pressed while typing in the line edit
for i in range(1000):
print(str(i), end="\r")
def start_game(self):
self.stackedWidget.setCurrentWidget(self.gamePage)
self.textBrowser.clear()
with open("list1.txt", "r") as f:
all_texts = f.readlines()
lines_of_text = len(all_texts)
self.textBrowser.append(all_texts[random.randint(0, lines_of_text-1)])
def goto_home_page(self):
self.stackedWidget.setCurrentWidget(self.startPage)
class SpaceFilter(QObject): # the event filter object
spacePressed = pyqtSignal() # the signal emited when space bar detected
def eventFilter(self, widget, event):
if event.type() == QEvent.KeyPress: # listen for key press events
if event.key() == Qt.Key.Key_Space: # if the key is the space bar
self.spacePressed.emit() # emit the signal
return False
Related
I am creating a GUI in Python using PySide2, this is my .ui file:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>main_window</class>
<widget class="QWidget" name="main_window">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="enabled">
<bool>true</bool>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1000</width>
<height>640</height>
</rect>
</property>
<property name="windowTitle">
<string>Testing App</string>
</property>
<layout class="QVBoxLayout" name="layout">
<item>
<layout class="QVBoxLayout" name="other_layout">
<item>
<widget class="QWidget" name="panel" native="true">
<layout class="QHBoxLayout" name="layout3">
<item>
<layout class="QVBoxLayout" name="layout4">
<item>
<layout class="QHBoxLayout" name="layout5">
<item>
<widget class="QLabel" name="lo">
<property name="text">
<string>X</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="resolution_x">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="inputMethodHints">
<set>Qt::ImhDigitsOnly</set>
</property>
<property name="text">
<string>175</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout6">
<item>
<widget class="QLabel" name="lo2">
<property name="text">
<string>Y</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="res2">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="inputMethodHints">
<set>Qt::ImhDigitsOnly</set>
</property>
<property name="text">
<string>150</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="layout7">
<item>
<layout class="QHBoxLayout" name="iterations_layout">
<item>
<widget class="QLabel" name="iterLab">
<property name="text">
<string>Num Passes</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="itr">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="inputMethodHints">
<set>Qt::ImhDigitsOnly</set>
</property>
<property name="text">
<string>20</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout8">
<item>
<widget class="QPushButton" name="reset_button">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>50</width>
<height>0</height>
</size>
</property>
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="text">
<string>Zoom</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="process_layout">
<item alignment="Qt::AlignLeft">
<widget class="QLabel" name="status">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>120</width>
<height>20</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>120</width>
<height>20</height>
</size>
</property>
<property name="text">
<string/>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item alignment="Qt::AlignRight">
<widget class="QLabel" name="procLab">
<property name="minimumSize">
<size>
<width>77</width>
<height>20</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>77</width>
<height>20</height>
</size>
</property>
<property name="text">
<string>#</string>
</property>
</widget>
</item>
<item alignment="Qt::AlignRight">
<widget class="QLineEdit" name="processes">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>50</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>50</width>
<height>2000</height>
</size>
</property>
<property name="inputMethodHints">
<set>Qt::ImhDigitsOnly</set>
</property>
<property name="text">
<string>8</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
I want to add a widget dynamically from my Python script to the main layout ('layout'):
app = QApplication(sys.argv)
f = MyWindow()
sys.exit(app.exec_())
class MyWindow(QWidget):
def __init__(self):
super(MyWindow, self).__init__(None)
ui_file = QtCore.QFile("./myui.ui")
ui_file.open(QtCore.QFile.ReadOnly)
loader = QtUiTools.QUiLoader()
self.window = loader.load(ui_file)
ui_file.close()
self.layout.addWidget(QLabel('Stuff'))
self.window.show()
However, I get the following error
self.layout.addWidget(QLabel('Stuff'))
AttributeError: 'builtin_function_or_method' object has no attribute 'addWidget'
I don't understand why self.layout doesn't have the property addWidget. I thought self.layout would have a reference to a QVBoxLayout object?
You have several errors:
The widget loaded from the .ui is not the MyWindow, on the other hand in PySide2 it is not possible to load a .ui to a widget class implemented by python (in PyQt5 if possible via uic.loadUi()) so the class should handle the widget.
On the other hand, do not use variable names that may conflict with the names of the methods, for example the QWidget class has a layout method so it is not recommended that you have an attribute with that name, a possible solution is to use findChild to get the layout:
import sys
from PySide2.QtCore import QObject, QFile
from PySide2.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PySide2.QtUiTools import QUiLoader
class Manager(QObject):
def __init__(self):
super(Manager, self).__init__(None)
ui_file = QFile("./myui.ui")
ui_file.open(QFile.ReadOnly)
loader = QUiLoader()
self.window = loader.load(ui_file)
ui_file.close()
lay = self.window.findChild(QVBoxLayout, "layout")
lay.addWidget(QLabel("Stuff"))
self.window.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
f = Manager()
sys.exit(app.exec_())
Another possible solution is to change the name of the layout to for example vlayout: <layout class="QVBoxLayout" name="vlayout">
import sys
from PySide2.QtCore import QObject, QFile
from PySide2.QtWidgets import QApplication, QLabel, QWidget
from PySide2.QtUiTools import QUiLoader
class Manager(QObject):
def __init__(self):
super(Manager, self).__init__(None)
ui_file = QFile("./myui.ui")
ui_file.open(QFile.ReadOnly)
loader = QUiLoader()
self.window = loader.load(ui_file)
ui_file.close()
self.window.vlayout.addWidget(QLabel("Stuff"))
self.window.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
f = Manager()
sys.exit(app.exec_())
Introduction:
I have got listWidget, that contains QListWidgetItem(s). On each of them I have got 3 buttons. 'Close' has to destroy QListWidgetItemcompletely, postpone has to close temporary, but will emerge on the next timeout of timer. So I have to save it to list or hide temporary.
UI part created in Designer.
Image:
Already tried:
I've tried #pyqtSlot(QListWidgetItem) def on_itemClicked(self, item), but the signal does NOT emit on clicking on buttons - only on clicking on the item itself. Even if you click on item, it will close, but it still has the 'frame of widget' of the QListWidgetItem, and it is still accessible by clicking. So it does NOT close the QListWidgetItem, but inst_pop_up.
Image:
I've found the solution, using eventFilter, but didn't figured out how to set it properly in Python.
I have tried to close the onePopUp from it's button 'Close' (uncomment here to see: self.pushButton_close.clicked.connect(self.close)), but it lefts 'frame of widget' as well.
The popupMain instance is initiated in init of MainWindow class:
self.pop_up_main = popupMain()
The Timer called in the MainWindow class:
self.pop_up_main.slot_add_new()
self.pop_up_main.show()
The problem is in onePopUp or popupMain
popup.py
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
class onePopUp(QWidget):
def __init__(self):
counter = 0
super(onePopUp, self).__init__(parent=None)
loadUi('one_pop_up.ui', self)
# self.setAttribute(Qt.WA_DeleteOnClose, on=True)
# self.pushButton_close.clicked.connect(self.close)
def closeEvent(self, event):
print('onePopUp : close event')
# super().close()
class popupMain(QDialog):
def __init__(self):
super(popupMain, self).__init__(parent=None)
loadUi('master_pop_up.ui', self)
self.listWidget.itemPressed.connect(self.on_itemClicked)
# Set up the user interface from Designer.
self.pushButton_add_extra_record.clicked.connect(self.slot_add_new)
# self.installEventFilter()
self.list_of_postponed_items = list()
#pyqtSlot(QListWidgetItem)
def on_itemClicked(self, item):
print('in on_itemClicked')
print('item is {}'.format(item))
# i = self.listWidget.item(item)
self.listWidget.removeItemWidget(item)
# def eventFilter(self, object, event):
#
# if event:
# print(event, repr(event))
# if object == self.dateEdit_date_of_record and event.type() == QMouseEvent.MouseButtonDblClick:
# print('dblclick!!!')
# self.dateEdit_date_of_record.setDisabled(False)
# return super(DialogAddItemRecords, self).eventFilter(object, event)
def slot_add_new(self):
print('im in slot_add_new')
# Creating a new list widget item whose parent is the listwidget itself
# QListWidgetItem * listWidgetItem = new QListWidgetItem(ui->listWidget);
list_widget_item = QListWidgetItem(self.listWidget)
list_widget_item.setFlags(list_widget_item.flags() & ~Qt.ItemIsSelectable)
# list_widget_item.setFlags(list_widget_item.flags() & ~Qt.ItemIsSelectable)
# Adding the item to the listwidget
# ui->listWidget->addItem(listWidgetItem);
self.listWidget.addItem(list_widget_item)
# Creating an object of the designed widget which is to be added to the listwidget
# TheWidgetItem * theWidgetItem = new TheWidgetItem;
inst_pop_up = onePopUp()
inst_pop_up.timeEdit.setTime(QTime.currentTime().addSecs(-15 * 60))
inst_pop_up.timeEdit_2.setTime(QTime.currentTime())
# Making sure that the listWidgetItem has the same size as the TheWidgetItem
# listWidgetItem->setSizeHint(theWidgetItem->sizeHint());
list_widget_item.setSizeHint(inst_pop_up.frameSize())
# print(inst_pop_up.dockWidget.testAttribute())
inst_pop_up.label_header.setText('test')
# Finally adding the itemWidget to the list
# ui->listWidget->setItemWidget(listWidgetItem, theWidgetItem);
self.listWidget.setItemWidget(list_widget_item, inst_pop_up)
# self.listWidget.addItem(list_widget_item, inst_pop_up)
# def slot_delete_item(self):
# list_widget_item = QListWidgetItem(self.listWidget)
# removeItemWidget
# popup_list_widget = QListWidget()
# one_pop_up_1 = onePopUp()
# popup_list_widget.addItem(one_pop_up_1)
def popup_main():
app = QApplication(sys.argv)
window = popupMain()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
popup_main()
//master_pop_up.ui
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>481</width>
<height>203</height>
</rect>
</property>
<property name="font">
<font>
<family>Segoe UI</family>
<pointsize>12</pointsize>
</font>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>icons/application-sidebar-list.png</normaloff>icons/application-sidebar-list.png</iconset>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_add_extra_record">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Add extra record</string>
</property>
<property name="icon">
<iconset>
<normaloff>icons/plus.png</normaloff>icons/plus.png</iconset>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_postpone_all">
<property name="text">
<string>Postpone all</string>
</property>
<property name="icon">
<iconset>
<normaloff>icons/alarm-clock-big_24_24.png</normaloff>icons/alarm-clock-big_24_24.png</iconset>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_close_all">
<property name="text">
<string>Close all</string>
</property>
<property name="icon">
<iconset>
<normaloff>icons/cross.png</normaloff>icons/cross.png</iconset>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>icons/gear.png</normaloff>icons/gear.png</iconset>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QListWidget" name="listWidget">
<property name="acceptDrops">
<bool>false</bool>
</property>
<property name="sizeAdjustPolicy">
<enum>QAbstractScrollArea::AdjustToContents</enum>
</property>
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="tabKeyNavigation">
<bool>true</bool>
</property>
<property name="showDropIndicator" stdset="0">
<bool>false</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::NoDragDrop</enum>
</property>
<property name="defaultDropAction">
<enum>Qt::IgnoreAction</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="horizontalScrollMode">
<enum>QAbstractItemView::ScrollPerItem</enum>
</property>
<property name="movement">
<enum>QListView::Static</enum>
</property>
<property name="isWrapping" stdset="0">
<bool>false</bool>
</property>
<property name="resizeMode">
<enum>QListView::Adjust</enum>
</property>
<property name="uniformItemSizes">
<bool>true</bool>
</property>
<property name="selectionRectVisible">
<bool>true</bool>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
//one_pop_up.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>373</width>
<height>114</height>
</rect>
</property>
<property name="font">
<font>
<family>Segoe UI</family>
<pointsize>12</pointsize>
</font>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<property name="locale">
<locale language="English" country="Germany"/>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QFrame" name="frame">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>48</height>
</size>
</property>
<property name="styleSheet">
<string notr="true">font: 12pt "Segoe UI";</string>
</property>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label_header">
<property name="font">
<font>
<family>Segoe UI</family>
<pointsize>12</pointsize>
<weight>50</weight>
<italic>false</italic>
<bold>false</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="pushButton_postpone">
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>Postpone</string>
</property>
<property name="icon">
<iconset>
<normaloff>icons/alarm-clock-blue_24_24.png</normaloff>icons/alarm-clock-blue_24_24.png</iconset>
</property>
<property name="iconSize">
<size>
<width>16</width>
<height>16</height>
</size>
</property>
<property name="autoDefault">
<bool>false</bool>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_close">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Segoe UI</family>
<pointsize>12</pointsize>
<weight>50</weight>
<italic>false</italic>
<bold>false</bold>
</font>
</property>
<property name="text">
<string>Close</string>
</property>
<property name="icon">
<iconset>
<normaloff>icons/prohibition.png</normaloff>icons/prohibition.png</iconset>
</property>
<property name="iconSize">
<size>
<width>16</width>
<height>16</height>
</size>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QFrame" name="">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label_23">
<property name="text">
<string>From</string>
</property>
</widget>
</item>
<item>
<widget class="QTimeEdit" name="timeEdit">
<property name="enabled">
<bool>true</bool>
</property>
<property name="wrapping">
<bool>false</bool>
</property>
<property name="frame">
<bool>true</bool>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
<property name="buttonSymbols">
<enum>QAbstractSpinBox::NoButtons</enum>
</property>
<property name="keyboardTracking">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>5</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>to</string>
</property>
</widget>
</item>
<item>
<widget class="QTimeEdit" name="timeEdit_2">
<property name="enabled">
<bool>true</bool>
</property>
<property name="frame">
<bool>true</bool>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
<property name="buttonSymbols">
<enum>QAbstractSpinBox::NoButtons</enum>
</property>
<property name="keyboardTracking">
<bool>false</bool>
</property>
<property name="showGroupSeparator" stdset="0">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="pushButton_add">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Add</string>
</property>
<property name="icon">
<iconset>
<normaloff>icons/arrow-curve.png</normaloff>icons/arrow-curve.png</iconset>
</property>
<property name="iconSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
What I have to do?
I have to distinguish what button sent the signal.
close (button 'Close')
take form QListWidget temporary('Postpone')
call method from another class MainWindow.add_record(#with the period of time on this widgetItem) (button 'Add record')
Also I have to do the postponing (button 'Postpone all') and closing to all (button 'Closing all') on popupMain buttons. But I even don't know hot to do on one item...
P.S. I have surfed everywhere, but can't figure out how to do it!
I have figured out how to do it. I've used list of tuples, that connected itemlistWidget and one_pop_up instance. I also used basic takeItem. It works perfectly.
I use hide in order to postpone the item.
class onePopUp(QWidget):
def __init__(self):
counter = 0
super(onePopUp, self).__init__(parent=None)
loadUi('one_pop_up.ui', self)
self.timeEdit.setTime(QTime.currentTime().addSecs(-15 * 60))
self.timeEdit_2.setTime(QTime.currentTime())
self.pushButton_postpone.clicked.connect(self.postpone_event)
self.pushButton_close.clicked.connect(self.close_event)
self.pushButton_add.clicked.connect(self.add_recordEvent)
def postpone_event(self):
print('in postpone_event at onePopUp')
print(self.sender())
print('_________out postpone_event at onePopUp')
return self.sender()
def close_event(self):
print('onePopUp : close event')
print('end_________onePopUp : close event')
return self.sender()
def add_recordEvent(self):
print('in add_recordEvent at onePopUp')
print(self.sender())
print('_________out add_recordEvent at onePopUp')
return self.sender()
class popupMain(QDialog):
def __init__(self, main_window=None):
super(popupMain, self).__init__(parent=None)
loadUi('master_pop_up.ui', self)
self.address_of_main_window = main_window
self.list_of_tuples_item_widget = list()
self.pushButton_show_main_window.clicked.connect(self.slot_show_main_window)
self.pushButton_postpone_all.clicked.connect(self.slot_postpone_all)
self.pushButton_add_extra_record.clicked.connect(self.slot_add_new)
self.pushButton_close_all.clicked.connect(self.slot_close_all)
def slot_show_main_window(self):
self.hide()
def slot_postpone_all(self):
j = 0
while j < self.listWidget.count():
item_to_unhide = self.listWidget.item(j)
print(item_to_unhide)
item_to_unhide.setHidden(True)
j += 1
def slot_close_all(self):
j = 0
while j < self.listWidget.count():
print(j, self.listWidget.count())
item_to_unhide = self.listWidget.item(j)
print(item_to_unhide)
# if not item_to_unhide.isHidden:
i = self.listWidget.takeItem(j)
print('i={}'.format(i))
# j += 1
def slot_add_new(self):
log('im in slot_add_new')
self.hide()
j = 0
while j < self.listWidget.count():
item_to_unhide = self.listWidget.item(j)
print(item_to_unhide)
if item_to_unhide.isHidden:
item_to_unhide.setHidden(False)
j += 1
# Creating a new list widget item whose parent is the listwidget itself
# QListWidgetItem * listWidgetItem = new QListWidgetItem(ui->listWidget);
list_widget_item = QListWidgetItem(self.listWidget)
list_widget_item.setFlags(list_widget_item.flags() & ~Qt.ItemIsSelectable)
# list_widget_item.setFlags(list_widget_item.flags() & ~Qt.ItemIsSelectable)
# Adding the item to the listwidget
# ui->listWidget->addItem(listWidgetItem);
self.listWidget.addItem(list_widget_item)
# Creating an object of the designed widget which is to be added to the listwidget
# TheWidgetItem * theWidgetItem = new TheWidgetItem;
inst_pop_up = onePopUp()
# inst_pop_up.timeEdit.setTime(QTime.currentTime().addSecs(-15 * 60))
# inst_pop_up.timeEdit_2.setTime(QTime.currentTime())
inst_pop_up.pushButton_postpone.pressed.connect(self.button_postpone_pressed_slot)
inst_pop_up.pushButton_close.clicked.connect(self.button_close_pressed_slot)
inst_pop_up.pushButton_add.pressed.connect(self.button_add_pressed_slot)
# Making sure that the listWidgetItem has the same size as the TheWidgetItem
# listWidgetItem->setSizeHint(theWidgetItem->sizeHint());
list_widget_item.setSizeHint(inst_pop_up.frameSize())
# print(inst_pop_up.dockWidget.testAttribute())
inst_pop_up.label_header.setText('test')
# Finally adding the itemWidget to the list
# ui->listWidget->setItemWidget(listWidgetItem, theWidgetItem);
self.listWidget.setItemWidget(list_widget_item, inst_pop_up)
self.list_of_tuples_item_widget.append((list_widget_item, inst_pop_up))
print('list_widget_item, inst_pop_up = {}, {}'.format(list_widget_item, inst_pop_up))
self.show()
def button_postpone_pressed_slot(self):
print('in button_postpone_pressed_slot at popupMain')
item = None
# print(self.sender())
pointer_to_widget = self.sender().parent().parent()
print(pointer_to_widget)
for list_item in self.list_of_tuples_item_widget:
if list_item[1] == pointer_to_widget:
item = list_item[0]
print('item is {}'.format(item))
item.setHidden(True)
print('_________out of button_postpone_pressed_slot at popupMain')
def button_close_pressed_slot(self):
print('in button_close_pressed_slot at popupMain')
item = None
# print(self.sender())
pointer_to_widget = self.sender().parent().parent()
print(pointer_to_widget)
for list_item in self.list_of_tuples_item_widget:
if list_item[1] == pointer_to_widget:
item = list_item[0]
print('item is {}'.format(item))
row = self.listWidget.row(item)
print('row={}'.format(row))
i = self.listWidget.takeItem(row)
print('i={}'.format(i))
print('__________out of button_close_pressed_slot at popupMain')
def button_add_pressed_slot(self):
print('in button_add_pressed_slot at popupMain')
onePopUp_instance = self.sender().parent().parent()
print(onePopUp_instance)
time_range_arg = dict(time_start=onePopUp_instance.timeEdit.time(),
time_end=onePopUp_instance.timeEdit_2.time())
self.address_of_main_window.add_item_records(time_range=time_range_arg)
print('_______out of button_add_pressed_slot at popupMain')
I have a QMainWindow with a menu and a mdiArea. When I click on a menu item I need to display a qDialog with, say, a datalist one it.
I'd like to build the QDialog with the datalist on it as it's own class; however, I do not know how to attach it to the mdiArea as a subwindow. Would it be possible to get a small example on how to do this?
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class CliDataBrowser(QDialog):
def __init__(self,parent=None):
super(CliDataBrowser,self).__init__(parent)
loadUi("CliReportsUI/clidata_browser.ui",self)
class MainApplication(QMainWindow):
def __init__(self,*args):
super(MainApplication,self).__init__(*args)
loadUi("CliReportsUI/clireportmain.ui",self)
#pyqtSlot()
def on_mnu_close_triggered(self):
sys.exit();
#pyqtSlot()
def on_mnu_master_triggered(self):
dataBrowser = CliDataBrowser(self) # <--- Need this to be a mdi subwindow
dataBrowser.show()
app = QApplication(sys.argv)
mainWin = MainApplication()
mainWin.show()
sys.exit(app.exec_())
clireportmain.ui:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CliReportMain</class>
<widget class="QMainWindow" name="CliReportMain">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1062</width>
<height>626</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>PPS Custom Client Reports</string>
</property>
<property name="windowIcon">
<iconset resource="clireports.qrc">
<normaloff>:/Images/clireports.png</normaloff>:/Images/clireports.png</iconset>
</property>
<widget class="QWidget" name="centralWidget">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="autoFillBackground">
<bool>false</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QMdiArea" name="mdiArea">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShadow">
<enum>QFrame::Plain</enum>
</property>
<property name="sizeAdjustPolicy">
<enum>QAbstractScrollArea::AdjustIgnored</enum>
</property>
<property name="background">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>20</red>
<green>38</green>
<blue>57</blue>
</color>
</brush>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1062</width>
<height>22</height>
</rect>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<widget class="QMenu" name="menuFile">
<property name="title">
<string>File</string>
</property>
<addaction name="mnu_Close"/>
</widget>
<widget class="QMenu" name="menuReports">
<property name="title">
<string>Reports</string>
</property>
</widget>
<widget class="QMenu" name="menuDatasets">
<property name="title">
<string>Datasets</string>
</property>
<addaction name="mnu_Master"/>
<addaction name="mnu_ICD10Master"/>
<addaction name="separator"/>
<addaction name="mnu_ProviderMaster"/>
<addaction name="mnu_InsuranceMaster"/>
</widget>
<addaction name="menuFile"/>
<addaction name="menuReports"/>
<addaction name="menuDatasets"/>
</widget>
<widget class="QStatusBar" name="statusBar"/>
<action name="mnu_Close">
<property name="text">
<string>Close</string>
</property>
</action>
<action name="mnu_Master">
<property name="text">
<string>Master</string>
</property>
</action>
<action name="mnu_ICD10Master">
<property name="text">
<string>ICD-10 Master</string>
</property>
</action>
<action name="mnu_ProviderMaster">
<property name="text">
<string>Provider Master</string>
</property>
</action>
<action name="mnu_InsuranceMaster">
<property name="text">
<string>Insurance Master</string>
</property>
</action>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources>
<include location="clireports.qrc"/>
</resources>
<connections/>
</ui>
You have to use the addSubWindow() method of QMdiArea:
#pyqtSlot()
def on_mnu_master_triggered(self):
dataBrowser = CliDataBrowser(self)
subWindow = self.mdiArea.addSubWindow(dataBrowser)
subWindow.show()
I decided to implement a simple version of GA algorithm. I firstly use Qt designer to create a .ui document which contains the component and layout of my GUI. Then try to connect it with the python, however, when comes to the self.dis_speed.insert(a), the window closes immediately. This is the whole code:
import sys
import random
import threading
import copy
from PyQt5 import QtCore, QtGui, uic, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,QTextEdit,QAction, QLabel,QSpinBox,QLineEdit
from PyQt5.QtCore import pyqtSlot
qtCreatorFile = 'assignment1_gui.ui' # Enter file here.
class Ui(QtWidgets.QMainWindow):
size=0
fit_dict={}
individual=[]
def __init__(self,parent=None):
super(Ui,self).__init__(parent=parent)
s=uic.loadUi(qtCreatorFile, self)
self.show()
self.but_start.clicked.connect(self.start)
self.dis_speed=s.dis_speed
self.dis_fit=s.dis_fit
self.dis_speed.setReadOnly(True)
self.dis_fit.setReadOnly(True)
def init_ind(a):
indi = [[] for l in range(a)]
for i in range(0,a):
for j in range(0,28):
indi[i].append(chr(random.randint(32, 127)))
return indi
def evaluate_fit(target,a):
count=0
for i in range(0,len(target)):
if target[i]==a[i]:
count+=1
return count
return(28-Levenshtein.hamming(str(target),str(a)))
def mutate(a):
for i in range(0,len(a)):
if(random.random()<(1/len(a))):
a[i]=chr(random.randint(32, 127))
return a
def crossover(a,b):
c=list()
for i in range(0,len(a)):
if random.random()<0.5:
c.append(a[i])
else:
c.append(b[i])
return c
def ga_cross(self,individual,target):
ind=copy.deepcopy(Ui.individual)
speed=0
printf=0
while(1):
a=random.randint(0,Ui.size-1)
b=random.randint(0,Ui.size-1)
if Ui.fit_dict[a]>Ui.fit_dict[b]:
parent1=ind[a]
else:
parent1=ind[b]
a=random.randint(0,Ui.size-1)
b=random.randint(0,Ui.size-1)
if Ui.fit_dict[a]>Ui.fit_dict[b]:
parent2=ind[a]
else:
parent2=ind[b]
child=Ui.mutate(Ui.crossover(parent1,parent2))
a=random.randint(0,Ui.size-1)
b=random.randint(0,Ui.size-1)
if Ui.fit_dict[a]>Ui.fit_dict[b]:
ind[b]=child
Ui.fit_dict[b]=Ui.evaluate_fit(target,child)
else:
ind[a]=child
Ui.fit_dict[a]=Ui.evaluate_fit(target,child)
speed+=1
if child==target:
break
if printf%10==0:
res=max(Ui.fit_dict.items(), key=lambda x: x[1])
Ui.tex(str(speed),str(ind[res[0]]))
printf+=1
#pyqtSlot()
def tex(self,a,b):
self.dis_speed.end(False)
self.dis_speed.insert(a) #close immediately
self.dis_fit.end(False)
self.dis_fit.insert(b)
#pyqtSlot()
def start(self):
target=list('methinks it is like a weasel')
Ui.size=int(self.spin_size.value())
Ui.individual=Ui.init_ind(Ui.size)
s=range(0,Ui.size)
ss=[0 for i in range(0,Ui.size)]
Ui.fit_dict=dict(zip(s,ss))
for i in range(0,Ui.size):
Ui.fit_dict[i]=Ui.evaluate_fit(target,Ui.individual[i])
Ui.ga_cross(self,Ui.individual,target)
Ui.ga_nocross(self,Ui.individual,target)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = Ui()
window.show()
sys.exit(app.exec_())
The following page is the .ui document in XML format which can be directly copied.
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>957</width>
<height>717</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QLabel" name="lab_title">
<property name="geometry">
<rect>
<x>100</x>
<y>40</y>
<width>811</width>
<height>41</height>
</rect>
</property>
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>36</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Comparision between GA with&without crossover</string>
</property>
</widget>
<widget class="QSpinBox" name="spin_size">
<property name="geometry">
<rect>
<x>590</x>
<y>120</y>
<width>111</width>
<height>41</height>
</rect>
</property>
<property name="minimum">
<number>100</number>
</property>
<property name="maximum">
<number>1000</number>
</property>
<property name="singleStep">
<number>100</number>
</property>
<property name="displayIntegerBase">
<number>10</number>
</property>
</widget>
<widget class="QLabel" name="label">
<property name="geometry">
<rect>
<x>310</x>
<y>130</y>
<width>271</width>
<height>20</height>
</rect>
</property>
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>18</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Please select the size of population:</string>
</property>
</widget>
<widget class="QPushButton" name="but_start">
<property name="geometry">
<rect>
<x>380</x>
<y>190</y>
<width>191</width>
<height>71</height>
</rect>
</property>
<property name="font">
<font>
<family>Wingdings 2</family>
<pointsize>24</pointsize>
</font>
</property>
<property name="text">
<string>START!</string>
</property>
</widget>
<widget class="QLabel" name="lab_nocr">
<property name="geometry">
<rect>
<x>30</x>
<y>330</y>
<width>241</width>
<height>51</height>
</rect>
</property>
<property name="font">
<font>
<family>Trajan Pro</family>
<pointsize>18</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Speed of no crossover:</string>
</property>
</widget>
<widget class="QLabel" name="lab_cr">
<property name="geometry">
<rect>
<x>590</x>
<y>330</y>
<width>211</width>
<height>51</height>
</rect>
</property>
<property name="font">
<font>
<family>Trajan Pro</family>
<pointsize>18</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Speed of crossover:</string>
</property>
</widget>
<widget class="QLabel" name="lab_nfit">
<property name="geometry">
<rect>
<x>130</x>
<y>410</y>
<width>111</width>
<height>16</height>
</rect>
</property>
<property name="font">
<font>
<family>YuMincho</family>
<pointsize>18</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Fittest Now:</string>
</property>
</widget>
<widget class="QLabel" name="lab_fit">
<property name="geometry">
<rect>
<x>690</x>
<y>410</y>
<width>111</width>
<height>16</height>
</rect>
</property>
<property name="font">
<font>
<family>YuMincho</family>
<pointsize>18</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Fittest Now:</string>
</property>
</widget>
<widget class="QLineEdit" name="dis_nspeed">
<property name="geometry">
<rect>
<x>270</x>
<y>340</y>
<width>51</width>
<height>31</height>
</rect>
</property>
</widget>
<widget class="QLineEdit" name="dis_nfit">
<property name="geometry">
<rect>
<x>20</x>
<y>440</y>
<width>341</width>
<height>41</height>
</rect>
</property>
</widget>
<widget class="QLineEdit" name="dis_speed">
<property name="geometry">
<rect>
<x>800</x>
<y>340</y>
<width>41</width>
<height>31</height>
</rect>
</property>
</widget>
<widget class="QLineEdit" name="dis_fit">
<property name="geometry">
<rect>
<x>600</x>
<y>440</y>
<width>291</width>
<height>41</height>
</rect>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>957</width>
<height>22</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
I am starting using QtCreator to create a UI for a little tool for Maya 2017. QtCreator gave me this .ui file :
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DockWidget</class>
<widget class="QDockWidget" name="DockWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>550</width>
<height>251</height>
</rect>
</property>
<property name="floating">
<bool>true</bool>
</property>
<property name="windowTitle">
<string>Attr Editor</string>
</property>
<widget class="QWidget" name="dockWidgetContents">
<widget class="QLineEdit" name="attr_value_textfield">
<property name="geometry">
<rect>
<x>130</x>
<y>128</y>
<width>391</width>
<height>20</height>
</rect>
</property>
<property name="toolTip">
<string>attr_value</string>
</property>
</widget>
<widget class="QLabel" name="label">
<property name="geometry">
<rect>
<x>227</x>
<y>20</y>
<width>97</width>
<height>25</height>
</rect>
</property>
<property name="font">
<font>
<family>Century Gothic</family>
<pointsize>16</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Attr Editor</string>
</property>
</widget>
<widget class="QPushButton" name="pushButton_2">
<property name="geometry">
<rect>
<x>240</x>
<y>180</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>Submit</string>
</property>
<property name="+command" stdset="0">
<string>submitCommand</string>
</property>
</widget>
<widget class="QLabel" name="label_3">
<property name="geometry">
<rect>
<x>20</x>
<y>130</y>
<width>80</width>
<height>16</height>
</rect>
</property>
<property name="font">
<font>
<family>Century Gothic</family>
</font>
</property>
<property name="text">
<string>Attribute Value</string>
</property>
</widget>
<widget class="QLineEdit" name="attr_name_textfield">
<property name="geometry">
<rect>
<x>130</x>
<y>78</y>
<width>391</width>
<height>20</height>
</rect>
</property>
<property name="toolTip">
<string>attr_name</string>
</property>
<property name="whatsThis">
<string/>
</property>
</widget>
<widget class="QPushButton" name="pushButton_3">
<property name="geometry">
<rect>
<x>440</x>
<y>180</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>Cancel</string>
</property>
<property name="+command" stdset="0">
<string>cancelCommand</string>
</property>
</widget>
<widget class="QPushButton" name="display_button">
<property name="geometry">
<rect>
<x>30</x>
<y>180</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>Display</string>
</property>
<property name="+command" stdset="0">
<string>displayCommand</string>
</property>
</widget>
<widget class="QLabel" name="label_2">
<property name="geometry">
<rect>
<x>20</x>
<y>80</y>
<width>82</width>
<height>16</height>
</rect>
</property>
<property name="font">
<font>
<family>Century Gothic</family>
</font>
</property>
<property name="text">
<string>Attribute Name</string>
</property>
</widget>
</widget>
</widget>
<resources/>
<connections/>
</ui>
And I have this code wich displays my UI :
import maya.cmds as cmds
from PySide2.QtWidgets import *
from PySide2.QtCore import *
if cmds.window(main_window, ex = True):
cmds.deleteUI(main_window)
main_window = cmds.loadUI(uiFile = "C:/Users/thornydre/Desktop/attreditorui.ui")
cmds.showWindow(main_window)
def displayCommand(e):
print(attr_name_textfield.text())
print(attr_value_textfield.text())
def submitCommand(e):
attr_name = attr_name_textfield.text()
attr_value = attr_value_textfield.text()
is_string = False
try:
new_attr_value = float(attr_value)
if float(attr_value) % 1 == 0:
new_attr_value = int(attr_value)
except:
is_string = True
new_attr_value = attr_value
print(new_attr_value)
for name in cmds.ls(sl = True):
if is_string:
cmds.setAttr(name + "." + attr_name, new_attr_value, type = "string")
else:
cmds.setAttr(name + "." + attr_name, new_attr_value)
def cancelCommand(e):
cmds.deleteUI(main_window, window = True)
And if I click on my display_button, I have an error :
# Result: dockWidgetContents|display_button #
# Error: AttributeError: file <maya console> line 12: 'bool' object has no attribute 'attr_name_textfield' #
I tried to do it with a subclass of QtWidgets.QWidget as I found somewhere on the internet, but I don't really found any tutorial on how to build it properly:
from PySide2 import QtCore, QtGui, QtWidgets, QtUiTools
class Interface(QtWidgets.QWidget):
def __init__(self, parent = None):
super(Interface, self).__init__(parent)
ui_filename = "C:/Users/thornydre/Desktop/attreditorui.ui"
ui_file = QtCore.QFile(ui_filename)
ui_file.open(QtCore.QFile.ReadOnly)
self.ui = QtUiTools.QUiLoader().load(ui_file, parentWidget=self)
ui_file.close()
def connectInterface(self):
QtCore.QtObject.connect(self.displayCommand, QtCore.SIGNAL("clicked()"), self.displayCommandWin)
def displayCommand(self):
print(self.attr_name_textfield.text())
print(self.attr_value_textfield.text())
def main():
global ui
ui = Interface()
if __name__ == "__main__":
main()
Same thing here, the UI shows up, but really nothing happens with clicking on the display_button
Your second try with the class seems good but it's completely normal that you can't execute displayCommand, your button is not connected to your method.
Juste delete your connectInterface method, and right after ui_file.close() copy this:
self.ui.display_button.clicked.connect(self.displayCommand)
It should work better :) (and you have to use the eyllanesc solution too to access to the widgets values)