I am trying to write a small app that compares xml. But right I am having a hard time doing the UI. I have a button that triggers a QFileDialog. I take the string input and populate a combobox. Unfortunately, the combobox stays empty. It seems to work when I hardcode it. But I am unable to get the app to do it dynamically. Is there something I am missing?
Here's the code:
import sys
from qtpy import QtCore, QtWidgets, uic
from qtpy.QtWidgets import QMainWindow, QApplication, QFileDialog
from qtpy.QtCore import QObject
class CompareSiteAndRepoWindow(QMainWindow):
def __init__(self):
super(CompareSiteAndRepoWindow,self).__init__()
uic.loadUi('CompareSiteAndRepo.ui',self)
self.BrowseLRPath.clicked.connect(self.browseFile)
self.buttonBox.rejected.connect(self.reject)
self.show()
def reject(self):
self.close()
def browseFile(self):
fileDiag = QFileDialog.getOpenFileName(self, 'Open file',
'c:\\',"xml/html (*.xml *.html)")
if(not fileDiag[0]):
print(fileDiag[0])
self.LRPathComboBox.addItem(fileDiag[0],0)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = CompareSiteAndRepoWindow()
sys.exit(app.exec())
the CompareSiteAndRepo.ui file
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CompareLabToSiteDLG</class>
<widget class="QMainWindow" name="CompareLabToSiteDLG">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>316</width>
<height>262</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="LRLabel">
<property name="text">
<string>Load Report</string>
</property>
</widget>
</item>
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="QComboBox" name="LRPathComboBox"/>
<widget class="QPushButton" name="BrowseLRPath">
<property name="text">
<string>Browse</string>
</property>
</widget>
</widget>
</item>
<item>
<widget class="QLabel" name="LP2Label">
<property name="text">
<string>LaunchPadData repo layout</string>
</property>
</widget>
</item>
<item>
<widget class="QSplitter" name="splitter_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="QComboBox" name="LP2RepoPath"/>
<widget class="QPushButton" name="BrowseLP2RepoPath">
<property name="text">
<string>Browse</string>
</property>
</widget>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>316</width>
<height>26</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
the problem is the statement if (not fileDiag[0]):, fileDialog[0] is a text that if we evaluate it as boolean will return True for any text except it is empty and if you deny it will be False if the text is not empty or True if it is, which is contrary to what you want:
fileDiag[0] not fileDiag[0]
+--------------+--------------+
"" True
"some text" False
One solution is to suppress the not:
if fileDiag[0]:
[...]
But another solution is to compare if the text is not empty as I show below:
def browseFile(self):
filename, _ = QFileDialog.getOpenFileName(self, 'Open file', 'c:\\',"xml/html (*.xml *.html)")
if filename != "":
self.LRPathComboBox.addItem(filename, 0)
Related
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
I'm trying to display in a PyQT5 Application a QListView to display some data.
My goal is to represent those data with a complex representation, not just line of text.
So, my QListView should "instantiate" a new QWidget loaded from a Ui file, and display each elements with that Ui representation.
My issue is with the layout of my Windows.
I have a main window, in which there is a QSplitter, the QListView is on the left, and on the right there are some widgets (Label, textedit, ...)
QMainWindow Designer:
Each line of my QListView I want to represent as this small widget:
Mini Widget Designer:
It seems that IF the QListView is inside a Widget Container like this:
Arbo object inspectors:
Then I have a weird behavior where child widget are displayed on top of each others:
ListView widget stacking:
But if I remove the container of the QListView
OkWindow Designer:
and the view of the inspector
They are properly displayed
Working as intented:
Any idea why?
Is there anything wrong with my code and the way to implement complex widget representation inside a Model/View QListView?
Here is the code of the application example:
import typing
from PyQt5 import QtCore, uic
from PyQt5.QtCore import QAbstractListModel, QModelIndex, Qt
from PyQt5.QtWidgets import (
QApplication,
QStyledItemDelegate,
QWidget, QMainWindow, )
class Editor(QWidget):
def __init__(self, index, parent=None):
super().__init__(parent)
uic.loadUi('step.ui', self)
value = index.model().data(index, Qt.ItemDataRole)
self.label.setText(value)
class MyListModel(QAbstractListModel):
def __init__(self, parent=None):
super().__init__(parent)
self._data_list = []
def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> typing.Any:
if role == Qt.ItemDataRole:
return self._data_list[index.row()]
def rowCount(self, parent: QModelIndex = QModelIndex()) -> int:
return len(self._data_list)
#property
def data_list(self):
return self._data_list
#data_list.setter
def data_list(self, data_list):
self.beginResetModel()
self._data_list = data_list.copy()
self.endResetModel()
class StyledItemDelegate(QStyledItemDelegate):
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.editor = None
def createEditor(self, parent, option, index):
self.editor = Editor(index, parent)
return self.editor
def sizeHint(self, option: 'QStyleOptionViewItem', index: QtCore.QModelIndex) -> QtCore.QSize:
if self.editor:
return self.editor.sizeHint()
else:
return super().sizeHint(option, index)
data = ["Apple", "Strawberry", "Cherry"]
class MainWindow(QMainWindow):
def __init__(self, qapp):
"""
Init main window
"""
super().__init__()
self.qapp = qapp
# Not working main_window ui file
# uic.loadUi('main_window.ui', self)
# Working main_window ui file
uic.loadUi('main_window_ok.ui', self)
self.load_data()
def load_data(self):
controller = MyCtrl(self)
controller.load_datalist()
class MyCtrl:
def __init__(self, parent: QMainWindow):
self.parent = parent
def load_datalist(self):
self.model = MyListModel()
self.model.data_list = data
self.parent.listView.setModel(self.model)
delegate = StyledItemDelegate(self.parent.listView)
self.parent.listView.setItemDelegate(delegate)
for i in range(self.model.rowCount()):
index = self.model.index(i, 0)
self.parent.listView.openPersistentEditor(index)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = MainWindow(app)
main.showMaximized()
sys.exit(app.exec_())
main_window.ui
<?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>800</width>
<height>642</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="QWidget" name="widget" native="true">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListView" name="listView"/>
</item>
</layout>
</widget>
<widget class="QWidget" name="widget_2" native="true">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QSlider" name="horizontalSlider">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<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_2">
<property name="text">
<string>Cancel</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>Ok</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>26</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
main_window_ok.ui
<?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>799</width>
<height>642</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="QListView" name="listView"/>
<widget class="QWidget" name="widget_2" native="true">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QSlider" name="horizontalSlider">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<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_2">
<property name="text">
<string>Cancel</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>Ok</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>799</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
step.ui file
<?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>387</width>
<height>173</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QDial" name="dial"/>
</item>
<item>
<widget class="QComboBox" name="comboBox"/>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
Creating a variable that stores a QWidget is useless and dangerous since for example you would only have the last widget or worse would be to access a widget that has been removed. Instead you must use a role to store and get the size, and the default role is Qt::SizeHintRole.
from PyQt5.uic import loadUi
from PyQt5.QtCore import QAbstractListModel, QModelIndex, Qt, QSize
from PyQt5.QtWidgets import (
QApplication,
QStyledItemDelegate,
QWidget,
QMainWindow,
)
class Editor(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
loadUi("step.ui", self)
class MyListModel(QAbstractListModel):
def __init__(self, parent=None):
super().__init__(parent)
self._data_list = list()
self._size_hints = dict()
def rowCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
return len(self._data_list)
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
return self._data_list[index.row()]
elif role == Qt.SizeHintRole:
return self._size_hints.get(index.row(), QSize(100, 30))
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.SizeHintRole:
self._size_hints[index.row()] = value
self.dataChanged.emit(index, index, (role,))
return True
return False
#property
def data_list(self):
return self._data_list
#data_list.setter
def data_list(self, data_list):
self.beginResetModel()
self._data_list = data_list.copy()
self.endResetModel()
class StyledItemDelegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = Editor(parent)
model = index.model()
model.setData(index, editor.sizeHint(), Qt.SizeHintRole)
return editor
def setEditorData(self, editor, index):
value = index.data()
editor.label.setText(value)
data = ["Apple", "Strawberry", "Cherry"]
class MainWindow(QMainWindow):
def __init__(self):
"""
Init main window
"""
super().__init__()
loadUi("main_window.ui", self)
class MyCtrl:
def __init__(self, view):
self.view = view
def load_datalist(self):
self.model = MyListModel()
self.model.data_list = data
self.view.listView.setModel(self.model)
delegate = StyledItemDelegate(self.view.listView)
self.view.listView.setItemDelegate(delegate)
for i in range(self.model.rowCount()):
index = self.model.index(i, 0)
self.view.listView.openPersistentEditor(index)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = MainWindow()
main.showMaximized()
controller = MyCtrl(main)
controller.load_datalist()
sys.exit(app.exec_())
I am a beginner with Qt and PySide with Python and I am facing a problem I don't know how to solve. I am working on FreeCAD and I try to design a simple window with push buttons but I can't make them work. When I click on them, their text should change but nothing happen.
Here is a piece of my code:
class ManageDialog:
def __init__(self, path):
self.form = FreeCADGui.PySideUic.loadUi(path)
self.form.setWindowTitle("Linked files manager")
QListWidgetItem("First item", self.form.listWidget)
QListWidgetItem("Second item", self.form.listWidget)
self.form.RemoveButton.clicked.connect(self.remove)
self.form.show()
def remove(self):
self.form.RemoveButton.setText("File removed")
path_to_ui = FreeCAD.getHomePath() + "/Mod/ThesisExistingBridges/ManageDialog.ui"
w = ManageDialog(path_to_ui)
My window is created according to a UI file done with Qt Creator. The design of the window is correct also and I can add items to a list widget for example but the buttons are not activated when clicked.
Here is a sample of UI file:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>494</width>
<height>459</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<widget class="QListWidget" name="listWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>471</width>
<height>401</height>
</rect>
</property>
</widget>
<widget class="QWidget" name="horizontalLayoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>420</y>
<width>195</width>
<height>31</height>
</rect>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="RemoveButton">
<property name="text">
<string>Remove</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="ReloadFromButton">
<property name="text">
<string>Reload from</string>
</property>
<property name="autoDefault">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QPushButton" name="OKButton">
<property name="geometry">
<rect>
<x>390</x>
<y>420</y>
<width>93</width>
<height>28</height>
</rect>
</property>
<property name="text">
<string>OK</string>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
I make it work in changing the method remove() in #static mode.
class ManageDialog:
def __init__(self, path):
self.form = FreeCADGui.PySideUic.loadUi(path)
self.form.setWindowTitle("Linked files manager")
QListWidgetItem("First item", self.form.listWidget)
QListWidgetItem("Second item", self.form.listWidget)
def clickedremove():
self.remove(self.form)
self.form.RemoveButton.clicked.connect(clickedremove)
self.form.show()
#staticmethod
def remove(f):
f.RemoveButton.setText("File removed")
path_to_ui = FreeCAD.getHomePath() + "/Mod/ThesisExistingBridges/ManageDialog.ui"
w = ManageDialog(path_to_ui)
It is maybe not the smartest way but it's working.
I would like to adjust the height of the stackedWidget so that the height of the QTextEdit widget below it matches the height of the buttons on the active page of the stackedWidget. While the 4 QPushButton on page extended take up the entire space of the stackedWidget, the 2 QPushButton on page normal appear vertically in the middle and still have free space above and below.
But the 2 QPushButton on page normal should be at the top and the QTextEdit widget should be enlarged upwards. How can this be done?
main.py
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
loadUi("mainwindow.ui", self)
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
mainwindow.ui
<?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>800</width>
<height>601</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<property name="locale">
<locale language="English" country="UnitedKingdom"/>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<widget class="QStackedWidget" name="stackedWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="normal" native="true">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QPushButton" name="normal_start_button">
<property name="text">
<string>Start</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="normal_stop_button">
<property name="text">
<string>Stop</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="extended">
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QPushButton" name="extended_quick_start_button">
<property name="text">
<string>Quick Start</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="extended_stop_button">
<property name="text">
<string>Stop</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="extended_slow_start_button">
<property name="text">
<string>Slow Start</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="extended_pause_button">
<property name="text">
<string>Pause</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item row="1" column="0">
<widget class="QTextEdit" name="output"/>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>24</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
Screenshot of page normal with only 2 QPushButton and unused space above and below:
Screenshot of page extended with 4 QPushButton and optimal use of the available space:
QStackedWidget takes as default height the default maximum height of the widget it contains, so in this case a possible solution is to set the height taking as reference the default height of the current widgets.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
loadUi("mainwindow.ui", self)
self.stackedWidget.currentChanged.connect(self.adjustHeight)
self.adjustHeight()
def adjustHeight(self):
h = self.stackedWidget.currentWidget().sizeHint().height()
self.stackedWidget.setFixedHeight(h)
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
def onTimeout():
sw = main_window.stackedWidget
sw.setCurrentIndex((sw.currentIndex() + 1) % sw.count())
# test
from PyQt5.QtCore import QTimer
timer = QTimer(timeout=onTimeout)
timer.start(1000)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I've created a simple GUI using qt designer and imported it into my python project. The main window comes up, and the menus/buttons are responsive, but I cannot manage to connect my QActions to custom functions (I did it for buttons though, and it works). The weird thing is that my custom function (on_action_clicked) is called once when I run the application, but not when I click on the menu items or icons of the toolbar (I tried connecting both). Below are the test codes. Am I missing something?
imbrowser3d.ui
<?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>851</width>
<height>649</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QGraphicsView" name="gv_image">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>731</width>
<height>501</height>
</rect>
</property>
</widget>
<widget class="QScrollBar" name="sb_index">
<property name="geometry">
<rect>
<x>0</x>
<y>510</y>
<width>701</width>
<height>20</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
<widget class="QScrollBar" name="sb_zeta">
<property name="geometry">
<rect>
<x>0</x>
<y>530</y>
<width>701</width>
<height>20</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
<widget class="QLabel" name="label_index">
<property name="geometry">
<rect>
<x>700</x>
<y>510</y>
<width>55</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>index</string>
</property>
</widget>
<widget class="QLabel" name="label_zeta">
<property name="geometry">
<rect>
<x>700</x>
<y>530</y>
<width>55</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>zeta</string>
</property>
</widget>
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>740</x>
<y>500</y>
<width>93</width>
<height>28</height>
</rect>
</property>
<property name="text">
<string>PushButton</string>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>851</width>
<height>26</height>
</rect>
</property>
<widget class="QMenu" name="menuFile">
<property name="title">
<string>File</string>
</property>
<addaction name="menu_open"/>
<addaction name="menu_save"/>
<addaction name="menu_load"/>
</widget>
<addaction name="menuFile"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<widget class="QToolBar" name="action_toolbar">
<property name="windowTitle">
<string>toolBar</string>
</property>
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="action_save_state"/>
</widget>
<action name="menu_open">
<property name="text">
<string>Open</string>
</property>
</action>
<action name="menu_save">
<property name="icon">
<iconset>
<normaloff>ui_icons/save_icon.png</normaloff>ui_icons/save_icon.png</iconset>
</property>
<property name="text">
<string>Save state</string>
</property>
</action>
<action name="menu_load">
<property name="text">
<string>Load state</string>
</property>
</action>
<action name="action_save_state">
<property name="icon">
<iconset>
<normaloff>ui_icons/save_icon.png</normaloff>ui_icons/save_icon.png</iconset>
</property>
<property name="text">
<string>Save state</string>
</property>
<property name="toolTip">
<string>Save state</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>
main.py
import sys
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication, QAction, QPushButton, QFileDialog
from PySide2.QtCore import QFile, QObject
class UiMainWindow(QObject):
def __init__(self, ui_file, parent=None):
super(UiMainWindow, self).__init__(parent)
ui_file = QFile(ui_file)
ui_file.open(QFile.ReadOnly)
loader = QUiLoader()
self.window = loader.load(ui_file)
ui_file.close()
self.btn = self.window.findChild(QPushButton, 'pushButton')
self.btn.clicked.connect(self.on_btn_clicked)
self.action_save = self.window.findChild(QAction, 'action_save_state')
self.action_save.triggered.connect(self.on_action_clicked('action clicked'))
self.window.show()
def on_action_clicked(self, txt):
print(txt)
def on_btn_clicked():
print('button clicked')
if __name__ == '__main__':
app = QApplication(sys.argv)
form = UiMainWindow('imbrowser3d.ui')
sys.exit(app.exec_())
You have 2 errors:
on_btn_clicked is a method of the class so it must have as the first parameter the instance, that is, self.
the connection is with the name of the function without evaluating, in your case the slot on_action_clicked you are evaluating it, so you are getting it printed at the beginning, for it there are 2 possible solutions: use partial or use a lambda function.
self.btn = self.window.findChild(QPushButton, 'pushButton')
self.btn.clicked.connect(self.on_btn_clicked)
self.action_save = self.window.findChild(QAction, 'action_save_state')
self.action_save.triggered.connect(partial(self.on_action_clicked, 'action clicked'))
# self.action_save.triggered.connect(lambda: self.on_action_clicked('action clicked')) # use lambda function
self.window.show()
def on_action_clicked(self, txt):
print(txt)
def on_btn_clicked(self):
print('button clicked')