Fit QTextEdit size to text size pyqt5 - python

I try to make the QTextEdit change its width value to the length of the text that is entered in it.
But the problem is that when using the resize property it does not do anything and does not change the size
I am obeying the length of the current word in the list and that value is the one I try to send as a property width() to the QTextEdit
to get something like this:
from PyQt5.QtWidgets import QMainWindow,QWidget,QVBoxLayout,QApplication,QTextEdit,QPushButton,QScrollArea
class Main(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.lista = ["one","two","abcdefghijklmn","zxyw","xyxyxyxyx"]
self.widget = QWidget(self)
self.layout = QVBoxLayout(self.widget)
self.area = QScrollArea(self)
self.area.resize(400,300)
self.area.setWidget(self.widget)
self.area.setWidgetResizable(True)
self.plain =QTextEdit(self)
self.plain.move(0,305)
self.plain.resize(400,50)
self.boton = QPushButton(self)
self.boton.move(0,360)
self.boton.setText("Press")
self.boton.clicked.connect(self.Test)
def Test(self):
for i in self.lista:
longitud = len(i)*6.3
print(longitud)
self.text = QTextEdit(self)
self.text.document().setPlainText(i)
self.text.setReadOnly(True)
self.text.resize(longitud,10)
self.layout.addWidget(self.text)
app = QApplication([])
m = Main()
m.show()
m.resize(600,400)
app.exec()
Actually what I need is that the QTextEdit that are created to fill the QScrollArea conform to the size of the length of text characters
This is the result I get but what I need is that the QTextEdit have the width() to where the line ends

Here is my attempt to solve this problem using font metrics to measure the size of the text box contents:
import sys
from PyQt5.QtGui import QFontMetrics
from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QApplication, QTextEdit, QPushButton, QScrollArea
class Main(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.lista = ["one", "two", "abcdefghijklmn", "zxyw", "xyxyxyxyx"]
self.widget = QWidget(self)
self.layout = QVBoxLayout(self.widget)
self.area = QScrollArea(self)
self.area.resize(400,300)
self.area.setWidget(self.widget)
self.area.setWidgetResizable(True)
self.plain = QTextEdit(self)
self.plain.move(0,305)
self.plain.resize(400,50)
self.boton = QPushButton(self)
self.boton.move(0,360)
self.boton.setText("Press")
self.boton.clicked.connect(self.Test)
def Test(self):
for i in self.lista:
text = QTextEdit(self)
text.document().setPlainText(i)
font = text.document().defaultFont()
fontMetrics = QFontMetrics(font)
textSize = fontMetrics.size(0, text.toPlainText())
w = textSize.width() + 10
h = textSize.height() + 10
text.setMinimumSize(w, h)
text.setMaximumSize(w, h)
text.resize(w, h)
text.setReadOnly(True)
self.layout.addWidget(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
m = Main()
m.show()
m.resize(600, 400)
sys.exit(app.exec_())
Result:

Related

Remove gap during add layout

I am seeing gap into QVBoxLayout when I am placing layout it does not look good, any idea to fix issue
#!/usr/bin/env python
import os
import sys
from PySide2.QtCore import Qt, QSize, QRegExp, QFile, QTextStream
from PySide2.QtGui import QKeySequence, QTextCharFormat, QBrush,QColor, QTextDocument, QTextCursor
from PySide2.QtWidgets import (QApplication, QDesktopWidget, QMainWindow,
QPlainTextEdit, QGridLayout, QGroupBox,
QFormLayout, QHBoxLayout, QLabel, QLineEdit,
QMenu, QMenuBar, QPushButton, QMessageBox,
QTextEdit, QVBoxLayout, QWidget, QAction)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.width = 1100
self.height = 700
self.set_main_window()
self.create_violation_text()
def set_main_window(self):
"""
Setting main window position
"""
self.setWindowTitle("GUI %s" %(os.path.abspath(__file__)))
self.setFixedSize(QSize(self.width, self.height))
wid = QDesktopWidget()
screen_width = wid.screen().frameGeometry().width()
screen_height = wid.screen().frameGeometry().height()
self.setGeometry(screen_width/2-self.width/2,
screen_height/2-self.height/2,
self.width, self.height)
def create_violation_text(self):
"""
creating main violation window which contain all violations
"""
self.plain_textedit = QPlainTextEdit()
self.plain_textedit.setLineWrapMode(QPlainTextEdit.NoWrap)
self.plain_textedit.setStyleSheet(
"""QPlainTextEdit {font-size: 14pt;
font-family: Courier;}""")
class ReviewWindow(MainWindow):
def __init__(self, waiver_files, app):
"""creating Review mode"""
super().__init__()
self.waiver_files = waiver_files
self.app = app
def create_widget(self):
self.create_text_finder()
self.create_violation_window()
#order matter
main_layout = QVBoxLayout()
main_layout.addWidget(self.text_finder)
main_layout.addWidget(self.create_violation_box)
#creating widgeth object as main window does not
#add layout directly it add only widget
window = QWidget()
window.setLayout(main_layout)
self.setCentralWidget(window)
def create_text_finder(self):
"""
create text finder which wil search string into document
"""
self.text_finder = QGroupBox()
layout = QHBoxLayout()
label = QLabel()
label.setText("Keyword:")
self.line_edit = QLineEdit()
self.line_edit.setText("Enter your search here")
push_button = QPushButton("Find")
push_button.clicked.connect(self.find_string_match)
layout.addWidget(label)
layout.addWidget(self.line_edit)
layout.addWidget(push_button)
self.text_finder.setLayout(layout)
def create_violation_window(self):
"""
creating violation window which contain text editor,
violation type and checkbox
"""
self.create_violation_box = QGroupBox()
layout = QGridLayout()
layout.addWidget(self.plain_textedit, 1, 0, 12, 1)
layout.setColumnMinimumWidth(0, 10)
self.create_violation_box.setLayout(layout)
def find_string_match(self):
"""
Adding string match operation
"""
#format for desire match
format = QTextCharFormat()
format.setBackground(QBrush(QColor("red")))
pattern = QRegExp(self.line_edit.text())
text_document = self.plain_textedit.document()
#Reverting if any
text_document.undo()
if pattern.isEmpty():
QMessageBox.warning("Search filed is empty")
else:
find_cursor = QTextCursor(text_document)
cursor = QTextCursor(text_document)
cursor.beginEditBlock()
while (not find_cursor.isNull() and not find_cursor.atEnd()):
found = False
find_cursor = text_document.find(pattern, find_cursor,
QTextDocument.FindWholeWords)
if (not find_cursor.isNull()):
found = True
find_cursor.movePosition(QTextCursor.WordRight,
QTextCursor.KeepAnchor)
find_cursor.mergeCharFormat(format)
cursor.endEditBlock()
if __name__ == '__main__':
app = QApplication(sys.argv)
cwd = os.path.dirname(__file__)
waiver_file = \[os.path.join(cwd, fdata) for fdata in os.listdir(cwd)\]
window = ReviewWindow(waiver_file, app)
window.create_widget()
window.show()
app.exec_()

How can I generate the buttons and connect them to different functions? [duplicate]

This question already has answers here:
How do I assert the identity of a PyQt5 signal?
(2 answers)
Closed 2 years ago.
I've created a search engine in PyQt5, using the code below:
import sys
from PyQt5.QtWidgets import (
QWidget, QLineEdit, QLabel, QScrollArea, QMainWindow,
QApplication, QHBoxLayout, QVBoxLayout, QSpacerItem, QSizePolicy, QCompleter, QPushButton
)
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
tlist = ['thing1', 'thing2', 'thing3', 'thing4']
class Label(QWidget):
def __init__(self, name):
super(Label, self).__init__()
self.name = name
self.lbl = QLabel(self.name)
self.lbl.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
self.btn = QPushButton("Preview")
self.btn.setMaximumSize(QtCore.QSize(100,100))
self.btn.clicked.connect(self.printsignal)
self.hbox = QHBoxLayout()
self.hbox.addWidget(self.lbl)
self.hbox.addWidget(self.btn)
self.setLayout(self.hbox)
def show(self):
for labels in [self, self.lbl]:
labels.setVisible(True)
def hide(self):
for labels in [self, self.lbl]:
labels.setVisible(False)
def printsignal(self):
print("clicked")
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__()
self.controls = QWidget()
self.controlsLayout = QVBoxLayout()
self.widgets = []
for name in tlist:
item = Label(name)
self.controlsLayout.addWidget(item)
self.widgets.append(item)
spacer = QSpacerItem(1, 1, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.controlsLayout.addItem(spacer)
self.controls.setLayout(self.controlsLayout)
self.scroll = QScrollArea()
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.controls)
self.searchbar = QLineEdit()
self.searchbar.textChanged.connect(self.update_display)
self.completer = QCompleter(tlist)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.searchbar.setCompleter(self.completer)
container = QWidget()
containerLayout = QVBoxLayout()
containerLayout.addWidget(self.searchbar)
containerLayout.addWidget(self.scroll)
container.setLayout(containerLayout)
self.setCentralWidget(container)
self.setGeometry(600, 100, 800, 600)
self.setWindowTitle('Search Engine')
def update_display(self, text):
for widget in self.widgets:
if text.lower() in widget.name.lower():
widget.show()
else:
widget.hide()
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
The problem I have is, all the buttons share the same function and I don't know how to make them have different signals, as they are generated automatically. Basically, if I run the code it will show up like
this:
and when I press any of the buttons, it will print "clicked" (as in printsignal function). What I want is a different function for each button. Is there a way to do that?
Normally you can use self.sender().text() to get text from QButton which generated signal.
But because you create own widget Label with QButton and QLabel and you want text from label so you can get directly self.name
def printsignal(self):
print("clicked", self.name)
eventually self.lbl.text()
def printsignal(self):
print("clicked", self.lbl.text())
Working code.
I removed show(), hide() because you don't need it
import sys
from PyQt5.QtWidgets import (
QWidget, QLineEdit, QLabel, QScrollArea, QMainWindow,
QApplication, QHBoxLayout, QVBoxLayout, QSpacerItem, QSizePolicy, QCompleter, QPushButton
)
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
tlist = ['thing1', 'thing2', 'thing3', 'thing4']
class Label(QWidget):
def __init__(self, name):
super().__init__()
self.name = name
self.lbl = QLabel(self.name)
self.lbl.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
self.btn = QPushButton("Preview")
self.btn.setMaximumSize(QtCore.QSize(100,100))
self.btn.clicked.connect(self.printsignal)
self.hbox = QHBoxLayout()
self.hbox.addWidget(self.lbl)
self.hbox.addWidget(self.btn)
self.setLayout(self.hbox)
def printsignal(self):
print("clicked", self.name)
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__()
self.controls = QWidget()
self.controlsLayout = QVBoxLayout()
self.widgets = []
for name in tlist:
item = Label(name)
self.controlsLayout.addWidget(item)
self.widgets.append(item)
spacer = QSpacerItem(1, 1, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.controlsLayout.addItem(spacer)
self.controls.setLayout(self.controlsLayout)
self.scroll = QScrollArea()
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.controls)
self.searchbar = QLineEdit()
self.searchbar.textChanged.connect(self.update_display)
self.completer = QCompleter(tlist)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.searchbar.setCompleter(self.completer)
container = QWidget()
containerLayout = QVBoxLayout()
containerLayout.addWidget(self.searchbar)
containerLayout.addWidget(self.scroll)
container.setLayout(containerLayout)
self.setCentralWidget(container)
self.setGeometry(600, 100, 800, 600)
self.setWindowTitle('Search Engine')
def update_display(self, text):
for widget in self.widgets:
if text.lower() in widget.name.lower():
widget.show()
else:
widget.hide()
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

PyQT5 QTabbar Expand tab header

I am writing a QTabwidget with only two tabs. But the tab headers (name) are not fitting the QTabwidget width. I want to fit the length of the tab bar (two tab headers)
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QMainWindow):
def __init__(self):
super().__init__()
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.show()
class MyTableWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
self.tabs = QTabWidget()
""" Here I want to fit the two tab
headers withthe QTabwidget width
"""
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300,200)
self.tabs.addTab(self.tab1,"Tab 1")
self.tabs.addTab(self.tab2,"Tab 2")
# Create first tab
self.tab1.layout = QVBoxLayout(self)
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
The size of tabs is computed using the hints given by the current QStyle.
Since QTabWidget uses the sizeHint of the tab bar to set the tab bar size and the sizeHint is usually based on the tabSizeHint(), you have to reimplement both:
sizeHint() is required in order to provide a width (or height) that is the same as the parent;
tabSizeHint() takes into account the base implementation of sizeHint() to compute the hint based on the contents of the tabs, and if it's less than the current size it suggests a size based on the available space divided by the tab count;
class TabBar(QtWidgets.QTabBar):
def sizeHint(self):
hint = super().sizeHint()
if self.isVisible() and self.parent():
if not self.shape() & self.RoundedEast:
# horizontal
hint.setWidth(self.parent().width())
else:
# vertical
hint.setHeight(self.parent().height())
return hint
def tabSizeHint(self, index):
hint = super().tabSizeHint(index)
if not self.shape() & self.RoundedEast:
averageSize = self.width() / self.count()
if super().sizeHint().width() < self.width() and hint.width() < averageSize:
hint.setWidth(averageSize)
else:
averageSize = self.height() / self.count()
if super().sizeHint().height() < self.height() and hint.height() < averageSize:
hint.setHeight(averageSize)
return hint
# ...
self.tabWidget = QtWidgets.QTabWidget()
self.tabWidget.setTabBar(TabBar(self.tabWidget))
Do note that this is a very basic implementation, there are some situations for which you might see the scroll buttons with very long tab names, even if theoretically there should be enough space to see them.
Inspired by this answer, I think you can override showEvent (and even resizeEvent) to calculate the new width and set it through stylesheets.
It is not canonical but it does the job.
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QTabWidget, QVBoxLayout
class App(QMainWindow):
def __init__(self):
super().__init__()
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.show()
class MyTableWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
self.tabs = QTabWidget()
self.tabs.tabBar().setExpanding(True)
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300, 200)
self.tabs.addTab(self.tab1, "Tab 1")
self.tabs.addTab(self.tab2, "Tab 2")
# Create first tab
self.tab1.layout = QVBoxLayout(self)
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
def resizeEvent(self, event):
super().resizeEvent(event)
self._set_tabs_width()
def showEvent(self, event):
super().showEvent(event)
self._set_tabs_width()
def _set_tabs_width(self):
tabs_count = self.tabs.count()
tabs_width = self.tabs.width()
tab_width = tabs_width / tabs_count
css = "QTabBar::tab {width: %spx;}" % tab_width
self.tabs.setStyleSheet(css)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Pyqt5 draw a line between two widgets

I am trying to use QPainter to draw a line between two widgets. If I use a simple function inside the first class it works. But, I want to create a separate class of a QPainter event, that I can call at the first class whenever I want. But, it is not working as expected. Can you help me to figure out why the QPainter class is not adding a line.
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.okButton = QPushButton("OK")
self.cancelButton = QPushButton("Cancel")
l1 = self.okButton.pos()
l2 = self.cancelButton.pos()
# This is to call the class to draw a line between those two widgets
a = QPaint(l1.x(), l1.y(), l2.x(), l2.y(),parent=self)
vbox = QVBoxLayout()
vbox.addWidget(self.okButton)
vbox.addWidget(self.cancelButton)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 150)
self.setWindowTitle('Buttons')
self.show()
class QPaint(QPainter):
def __init__(self, x1, y1, x2, y2, parent=None):
super().__init__()
def paintEvent(self, event):
self.setPen(Qt.red)
self.drawLine(x1,y1,x2,y2)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Widgets can only be painted in the widget's paintEvent method, so if you don't want to paint it in the same class then you can use multiple inheritance. On the other hand, the initial positions you use to paint will be the positions before showing that they are 0 making no line is painted but a point so it is better to track the positions using an event filter.
import sys
from PyQt5.QtCore import QEvent
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
class Drawer:
def paintEvent(self, event):
painter = QPainter(self)
painter.drawLine(self.p1, self.p2)
class Example(QWidget, Drawer):
def __init__(self, parent=None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.okButton = QPushButton("OK")
self.cancelButton = QPushButton("Cancel")
vbox = QVBoxLayout(self)
vbox.addWidget(self.okButton)
vbox.addWidget(self.cancelButton)
self.setGeometry(300, 300, 300, 150)
self.setWindowTitle("Buttons")
self.p1, self.p2 = self.okButton.pos(), self.cancelButton.pos()
self.okButton.installEventFilter(self)
self.cancelButton.installEventFilter(self)
def eventFilter(self, o, e):
if e.type() == QEvent.Move:
if o is self.okButton:
self.p1 = self.okButton.pos()
elif o is self.cancelButton:
self.p2 = self.cancelButton.pos()
self.update()
return super().eventFilter(o, e)
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())

Button is not working on the second window of pyqt5

I'm making a first come first served scheduler using pyqt5.
I have the main window which includes textbox asking the user for scheduler type, when button "GO" is clicked, the second window is opened which asks the user for more information about the scheduler like process numbers and burst time .
When button "GO" on the second window is clicked, a Gantt chart should appear after processing the information.
The problem is that the button on the second window is not working at all.
I have found a similar question, but I didn't quite got the solution, plus I'm not using JSON.
Code:
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import QMainWindow,QApplication, QComboBox, QDialog,QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout,QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox, QTextEdit,QVBoxLayoutQSpinBox, QTextEdit, QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
import matplotlib.pyplot as plt
import numpy as np
import linked_list
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My Program")
self.setWindowIcon(QtGui.QIcon("download.jpg"))
self.setGeometry(50,50,500,300)
self.home()
self.show()
def home(self):
self.label2=QLabel(self)
self.label2.setText("Type of Scheduler")
self.label2.move(10,50)
self.textbox2=QLineEdit(self)
self.textbox2.move(100,50)
self.button=QPushButton("Go",self)
self.button.move(0,200)
self.button.clicked.connect(self.runcode)
def runcode(self):
schedular_type=self.textbox2.text()
if(schedular_type=="FCFS"):
self.close()
self.fcfs=Window2(self)
Self.fcfs.__init__()
class Window2(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My Program")
self.setWindowIcon(QtGui.QIcon("download.jpg"))
self.setGeometry(50,50,500,300)
self.home()
self.show()
def home(self):
self.label1=QLabel(self)
self.label1.setText("No of Processes")
self.label1.move(10,0) #col ,row
self.textbox=QLineEdit(self)
self.textbox.move(100,0)
self.label3=QLabel(self)
self.label3.setText("Processess Names")
self.label3.move(10,100)
self.label4=QLabel(self)
self.label4.setText("Burst Time")
self.label4.move(120,100)
self.label5=QLabel(self)
self.label5.setText("Arrival Time")
self.label5.move(200,100)
self.names=QLineEdit(self)
self.names.move(10,150)
# self.names.resize(100,160)
self.burst=QLineEdit(self)
self.burst.move(120,150)
#self.burst.resize(100,160)
self.arrival=QLineEdit(self)
self.arrival.move(250 ,150)
#self.arrival.resize(100,160)
#self.textEdit=QTextEdit(self)
#self.textEdit.move(20,250)
self.button=QPushButton("Go",self)
self.button.move(0,200)
self.button.clicked.connect(self.fcfs)
def fcfs(self):
//
def main():
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Set a parent to second window, also you are calling ____init____ method of Window2 twice.
Here is the fixed code :
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QMainWindow, QApplication, QComboBox,
QDialog, QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox,
QHBoxLayout, QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox,
QTextEdit, QVBoxLayout)
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
import matplotlib.pyplot as plt
import numpy as np
import linked_list
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My Program")
self.setWindowIcon(QtGui.QIcon("download.jpg"))
self.setGeometry(50, 50, 500, 300)
self.home()
self.show()
def home(self):
self.label2 = QLabel(self)
self.label2.setText("Type of Scheduler")
self.label2.move(10, 50)
self.textbox2 = QLineEdit(self)
self.textbox2.move(100, 50)
self.button = QPushButton("Go", self)
self.button.move(0, 200)
self.button.clicked.connect(self.runcode)
def runcode(self):
schedular_type = self.textbox2.text()
if(schedular_type == "FCFS"):
self.close()
fcfs = Window2(self)
# Do not call __init__ explicitly below
# fcfs.__init__()
class Window2(QMainWindow):
def __init__(self,parent=None):
super().__init__(parent)
# always try to set a parent
self.setWindowTitle("My Program")
self.setWindowIcon(QtGui.QIcon("download.jpg"))
self.setGeometry(50, 50, 500, 300)
self.home()
self.show()
def home(self):
self.label1 = QLabel(self)
self.label1.setText("No of Processes")
self.label1.move(10, 0) # col ,row
self.textbox = QLineEdit(self)
self.textbox.move(100, 0)
self.label3 = QLabel(self)
self.label3.setText("Processess Names")
self.label3.move(10, 100)
self.label4 = QLabel(self)
self.label4.setText("Burst Time")
self.label4.move(120, 100)
self.label5 = QLabel(self)
self.label5.setText("Arrival Time")
self.label5.move(200, 100)
self.names = QLineEdit(self)
self.names.move(10, 150)
# self.names.resize(100,160)
self.burst = QLineEdit(self)
self.burst.move(120, 150)
# self.burst.resize(100,160)
self.arrival = QLineEdit(self)
self.arrival.move(250, 150)
# self.arrival.resize(100,160)
# self.textEdit=QTextEdit(self)
# self.textEdit.move(20,250)
self.button = QPushButton("Go", self)
self.button.move(0, 200)
self.button.clicked.connect(self.fcfs)
def fcfs(self):
no_of_process = self.textbox.text()
process_names = self.names.text()
burst_time = self.burst.text()
arrival_time = self.arrival.text()
names_list = process_names.split()
burst_list = burst_time.split()
arrival_list = arrival_time.split()
# integer conversion
burst_list = [int(i) for i in burst_list]
arrival_list = [int(i) for i in arrival_list]
no_of_process = int(no_of_process)
ls = LinkedList()
i = 0
while i < no_of_process:
ls.append(names_list[i], burst_list[i], arrival_list[i])
i = i + 1
time = arrival_list[0]
j = 0
start = []
end = []
name = []
while j < (ls.size()):
while(time < arrival_list[j]):
time = time + 1
start.append(time)
time = time + burst_list[j]
end.append(time)
name.append(names_list[j])
j = j + 1
waiting_time = 0
k = 0
average_waiting = 0
while k < (ls.size()):
waiting_time = waiting_time + \
end[k] - arrival_list[k] - burst_list[k]
average_waiting = waiting_time / ls.size()
k = k + 1
x = name
begin = np.array(start)
end = np.array(end)
plt.barh(range(len(begin)), end - begin, left=begin)
plt.yticks(range(len(begin)), x)
#plt.text(0.6,1.5,('average waiting is ',average_waiting))
plt.annotate(("average waiting is", average_waiting), xy=(0.5, 1.49))
plt.show()
def main():
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
the crucial part is:
def __init__(self,parent=None):
super().__init__(parent)

Categories