change expanding space of nested layouts in pyqt - python

I want to seperate the widgets of the mainwindow into 3 layouts and add them into a mainlayout
the center layout contains a tablewidget and shoud have a bigger width then the left/right one. so far I did not found a way to use a grid layout and adjust each column width individualy.
therefore I tryed to use 3 vboxlayouts and insert them into an hboxlayout
what if read so far is that the widgets size are fixed so they expand at the same rate if stretched.
is there an easier way to make the center layout widht bigger with for example inserting an spacer without changing the SizePolicy of each widget ?
import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
class Stretchme(qtw.QWidget):
def __init__(self):
super().__init__()
# # View
table_widget = qtw.QTableWidget()
# -----interface--widgets--------------------------#
# -------- parameter_widgets------------#
parameter_label = qtw.QLabel("Parameter")
test_time_label = qtw.QLabel("Time")
self.clocktime = qtw.QTimeEdit()
test_date_label = qtw.QLabel("Date")
self.date_time = qtw.QDateEdit()
grob_fein_label = qtw.QLabel("Grobe")
grob_fein_combo_box = qtw.QComboBox()
vr_label = qtw.QLabel("Lame")
self.vr_feuchte_input = qtw.QLineEdit()
# leftvboxlayout
left_vboxlayout = qtw.QVBoxLayout()
left_vboxlayout.addStretch(1)
left_vboxlayout.addWidget(test_time_label)
left_vboxlayout.addWidget(self.clocktime)
left_vboxlayout.addWidget(test_date_label)
left_vboxlayout.addWidget(self.date_time)
left_vboxlayout.addWidget(grob_fein_label)
left_vboxlayout.addWidget(grob_fein_combo_box)
left_vboxlayout.addWidget(vr_label)
left_vboxlayout.addWidget(self.vr_feuchte_input)
# centervboxlayout
center_voboxlayout = qtw.QVBoxLayout()
#
# center_voboxlayout.addStretch()
# center_voboxlayout.setStretchFactor()
# center_voboxlayout.addSpacing()
# center_voboxlayout.setStretchFactor()
#
# table_widget.setMinimumSize(90,80)
center_voboxlayout.addWidget(table_widget)
# righvobxlayout
# buttons
self.button_1 = qtw.QPushButton("Button 1")
self.button_2 = qtw.QPushButton("Button 2")
self.button_2 = qtw.QPushButton("Button 3")
rightvboxlayout = qtw.QVBoxLayout()
rightvboxlayout.addStretch(1)
rightvboxlayout.addWidget(self.button_1)
rightvboxlayout.addWidget(self.button_2)
rightvboxlayout.addWidget(self.button_2)
#
#
# Separador = qtw.QFrame()
# # Separador.Shape(QFrame.HLine)
# Separador.setFrameShape(qtw.QFrame.HLine)
#
# Separador.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
# Separador.setLineWidth(5)
# # HPOUT1_layout = QVBoxLayout()
# # HPOUT1_layout.addLayout(HPOUT1L_layout)
# # HPOUT1_layout.addWidget(Separador)
# # HPOUT1_layout.addLayout(HPOUT1R_layout)
## main layout
self.qhboxlayout = qtw.QHBoxLayout()
self.qhboxlayout.addLayout(left_vboxlayout)
# self.qhboxlayout.addWidget(Separador)
self.qhboxlayout.addLayout(center_voboxlayout)
self.qhboxlayout.addLayout(rightvboxlayout)
#
# ### Main Grid
# -------------------------------------------------- #
selected_color = qtg.QColor(0,0,255)
# self.setGeometry(300, 300, 1850, 950)
self.setStyleSheet("background-color: {}")
self.setLayout(self.qhboxlayout)
self.show()
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
w = Stretchme()
sys.exit(app.exec_())

Try this :
you will decide how much space allocate for each layout, by the following way :
self.qhboxlayout.addLayout(left_vboxlayout,20)
self.qhboxlayout.addLayout(center_voboxlayout,80)
self.qhboxlayout.addLayout(rightvboxlayout,20)
Your Code
import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
class Stretchme(qtw.QWidget):
def __init__(self):
super().__init__()
# # View
table_widget = qtw.QTableWidget()
# -----interface--widgets--------------------------#
# -------- parameter_widgets------------#
parameter_label = qtw.QLabel("Parameter")
test_time_label = qtw.QLabel("Time")
self.clocktime = qtw.QTimeEdit()
test_date_label = qtw.QLabel("Date")
self.date_time = qtw.QDateEdit()
grob_fein_label = qtw.QLabel("Grobe")
grob_fein_combo_box = qtw.QComboBox()
vr_label = qtw.QLabel("Lame")
self.vr_feuchte_input = qtw.QLineEdit()
# leftvboxlayout
left_vboxlayout = qtw.QVBoxLayout()
left_vboxlayout.addStretch(1)
left_vboxlayout.addWidget(test_time_label)
left_vboxlayout.addWidget(self.clocktime)
left_vboxlayout.addWidget(test_date_label)
left_vboxlayout.addWidget(self.date_time)
left_vboxlayout.addWidget(grob_fein_label)
left_vboxlayout.addWidget(grob_fein_combo_box)
left_vboxlayout.addWidget(vr_label)
left_vboxlayout.addWidget(self.vr_feuchte_input)
# centervboxlayout
center_voboxlayout = qtw.QVBoxLayout()
#
# center_voboxlayout.addStretch()
# center_voboxlayout.setStretchFactor()
# center_voboxlayout.addSpacing()
# center_voboxlayout.setStretchFactor()
#
# table_widget.setMinimumSize(90,80)
center_voboxlayout.addWidget(table_widget)
# righvobxlayout
# buttons
self.button_1 = qtw.QPushButton("Button 1")
self.button_2 = qtw.QPushButton("Button 2")
self.button_2 = qtw.QPushButton("Button 3")
rightvboxlayout = qtw.QVBoxLayout()
rightvboxlayout.addStretch(1)
rightvboxlayout.addWidget(self.button_1)
rightvboxlayout.addWidget(self.button_2)
rightvboxlayout.addWidget(self.button_2)
#
#
# Separador = qtw.QFrame()
# # Separador.Shape(QFrame.HLine)
# Separador.setFrameShape(qtw.QFrame.HLine)
#
# Separador.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
# Separador.setLineWidth(5)
# # HPOUT1_layout = QVBoxLayout()
# # HPOUT1_layout.addLayout(HPOUT1L_layout)
# # HPOUT1_layout.addWidget(Separador)
# # HPOUT1_layout.addLayout(HPOUT1R_layout)
## main layout
self.qhboxlayout = qtw.QHBoxLayout()
self.qhboxlayout.addLayout(left_vboxlayout,20)
self.qhboxlayout.addLayout(center_voboxlayout,80)
self.qhboxlayout.addLayout(rightvboxlayout,20)
#
# ### Main Grid
# -------------------------------------------------- #
selected_color = qtg.QColor(0,0,255)
# self.setGeometry(300, 300, 1850, 950)
self.setStyleSheet("background-color: {}")
self.setLayout(self.qhboxlayout)
self.show()
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
w = Stretchme()
sys.exit(app.exec_())

You have to set a stretch factor when adding the central layout:
# ...
self.qhboxlayout.addLayout(center_voboxlayout, stretch=1)
# ...

Related

how to display 2 buttons and 2 labels using pyqt5 in python?

I want to display in a QWidget windows 2 buttons and 2 label where the 2 buttons as on the same horizontal layout. and each button will have under it the label.
For this i use to library :
QHBoxLayout
QVBoxLayout
When i run the script it doesn't display all the created widgets.
it display 1 button and 1 label.
code:
import sys
from PyQt5 import QtWidgets
def basicWindow():
app = QtWidgets.QApplication(sys.argv)
windowExample = QtWidgets.QWidget()
buttonA = QtWidgets.QPushButton('Click!')
labelA = QtWidgets.QLabel('Label Example')
buttonb = QtWidgets.QPushButton('Click 2!')
labelb = QtWidgets.QLabel('Label Example 2')
v_box_H = QtWidgets.QHBoxLayout()
# v_box_H2 = QtWidgets.QHBoxLayout()
v_box = QtWidgets.QVBoxLayout()
v_box.addWidget(buttonA)
v_box.addWidget(labelA)
v_box2 = QtWidgets.QVBoxLayout()
v_box2.addWidget(buttonb)
v_box2.addWidget(labelb)
v_box_H.addLayout(v_box)
windowExample.setLayout(v_box)
windowExample.setLayout(v_box2)
windowExample.setWindowTitle('PyQt5 Lesson 4')
windowExample.show()
sys.exit(app.exec_())
basicWindow()
If you run the application from terminal / CMD you get the error:
QWidget::setLayout: Attempting to set QLayout "" on QWidget "", when the QLayout already has a parent
Try it:
import sys
from PyQt5 import QtWidgets
def basicWindow():
app = QtWidgets.QApplication(sys.argv)
windowExample = QtWidgets.QWidget()
buttonA = QtWidgets.QPushButton('Click!')
labelA = QtWidgets.QLabel('Label Example')
buttonb = QtWidgets.QPushButton('Click 2!')
labelb = QtWidgets.QLabel('Label Example 2')
v_box_H = QtWidgets.QHBoxLayout(windowExample) # + windowExample
# v_box_H2 = QtWidgets.QHBoxLayout()
v_box = QtWidgets.QVBoxLayout()
v_box.addWidget(buttonA)
v_box.addWidget(labelA)
v_box2 = QtWidgets.QVBoxLayout()
v_box2.addWidget(buttonb)
v_box2.addWidget(labelb)
v_box_H.addLayout(v_box)
v_box_H.addLayout(v_box2) # +++
# windowExample.setLayout(v_box) # -
# windowExample.setLayout(v_box2) # -
windowExample.setWindowTitle('PyQt5 Lesson 4')
windowExample.show()
sys.exit(app.exec_())
basicWindow()

How add a background image on a QWidget and add positional QLineedit on top of it?

I'm trying to set a background image on a QWidget and have some QlineEdit on top of it.
So for know I have this code
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class Model_GUI(QMainWindow):
def __init__(self, parent= None ):
super(Model_GUI, self).__init__()
self.left = 0
self.top = 0
self.width = 800
self.height = 800
self.resize(self.width,self.height)
GB = QGroupBox(" Gain ")
GB_layout = QHBoxLayout()
label = QLabel('A')
edit = QLineEdit('1')
GB_layout.addWidget(label)
GB_layout.addWidget(edit)
GB.setLayout(GB_layout)
GB2 = QGroupBox(" Gain ")
GB_layout2 = QHBoxLayout()
label2 = QLabel('A')
edit2 = QLineEdit('1')
GB_layout2.addWidget(label2)
GB_layout2.addWidget(edit2)
GB2.setLayout(GB_layout2)
#Graph
Graph = graph()
self.CentralWidget = QWidget()
self.globallayout = QHBoxLayout()
self.globallayout.addWidget(GB)
self.globallayout.addWidget(Graph)
self.globallayout.addWidget(GB2)
self.CentralWidget.setLayout(self.globallayout)
self.setCentralWidget(self.CentralWidget)
class graph(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(600,600)
oImage = QImage("img.png")
sImage = oImage.scaled(QSize(self.width(), self.height())) # resize Image to widgets size
palette = QPalette()
palette.setBrush(10, QBrush(sImage)) # 10 = Windowrole
self.setPalette(palette)
self.label1 = QLabel('Param1', self)
self.edit1 = QLineEdit('1', self)
self.label2 = QLabel('Param2', self)
self.edit2 = QLineEdit('10', self)
self.label1.move(50, 50)
self.edit1.move(500, 50)
self.label2.move(50, 500)
self.edit2.move(500, 500)
def main():
app = QApplication(sys.argv)
ex = Model_GUI(app)
ex.setWindowTitle('window')
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()
but when I execute it I don't have the image in the QWidget (in the middle).
If I replace ex = Model_GUI(app)with ex = graph(), I have the correct expectation :
I don't understand why the image is correctly set when I'm using the QWidget alone but it isn't set right when I embedded it in a QMainWindow?
QWidgets use their QPalette.Window role only if they are top level widgets (as in "windows"), otherwise the parent background is used instead unless the autoFillBackground property (which is false by default) is true.
Just set the property in the widget initialization:
self.setAutoFillBackground(True)

How to create a grid of splitters

What I'm trying to do is add splitter to a QGridLayout in order to resize the layout with the mouse. So for instance with this :
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.setFixedWidth(300)
self.setFixedHeight(100)
self.wid = QWidget()
self.setCentralWidget(self.wid)
self.grid = QGridLayout()
l_a = QLabel('A')
l_b = QLabel('B')
l_c = QLabel('C')
l_d = QLabel('D')
l_e = QLabel('E')
l_f = QLabel('F')
l_g = QLabel('G')
l_h = QLabel('H')
l_i = QLabel('I')
self.grid.addWidget(l_a, 0, 0)
self.grid.addWidget(l_b, 0, 1)
self.grid.addWidget(l_c, 0, 2)
self.grid.addWidget(l_d, 1, 0)
self.grid.addWidget(l_e, 1, 1)
self.grid.addWidget(l_f, 1, 2)
self.grid.addWidget(l_g, 2, 0)
self.grid.addWidget(l_h, 2, 1)
self.grid.addWidget(l_i, 2, 2)
self.wid.setLayout(self.grid)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
ex.show()
sys.exit(app.exec_( ))
I get this:
What I would like is instead of the colored line, have the possibility to click and drag vertically (for green lines) and horizontally (for red lines) the grid borders.
I tried something with QSplitter directly, but I end up with:
The Horizontal splits are okay, but the vertical ones are not aligned any more:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.setFixedWidth(300)
self.setFixedHeight(100)
self.wid = QWidget()
self.setCentralWidget(self.wid)
# self.grid = QGridLayout()
self.globallayout = QVBoxLayout()
self.split_V = QSplitter(Qt.Vertical)
l_a = QLabel('A')
l_b = QLabel('B')
l_c = QLabel('C')
l_d = QLabel('D')
l_e = QLabel('E')
l_f = QLabel('F')
l_g = QLabel('G')
l_h = QLabel('H')
l_i = QLabel('I')
split_H = QSplitter(Qt.Horizontal)
split_H.addWidget(l_a)
split_H.addWidget(l_b)
split_H.addWidget(l_c)
self.split_V.addWidget(split_H)
split_H = QSplitter(Qt.Horizontal)
split_H.addWidget(l_d)
split_H.addWidget(l_e)
split_H.addWidget(l_f)
self.split_V.addWidget(split_H)
split_H = QSplitter(Qt.Horizontal)
split_H.addWidget(l_g)
split_H.addWidget(l_h)
split_H.addWidget(l_i)
self.split_V.addWidget(split_H)
self.globallayout.addWidget(self.split_V)
self.wid.setLayout(self.globallayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
ex.show()
sys.exit(app.exec_( ))
Update
I think I almost found a solution where a function is used so that whenever the vertical splits are changed, it re-aligns them:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.setFixedWidth(300)
self.setFixedHeight(100)
self.wid = QWidget()
self.setCentralWidget(self.wid)
# self.grid = QGridLayout()
self.globallayout = QVBoxLayout()
self.split_V = QSplitter(Qt.Vertical)
l_a = QLabel('A')
l_b = QLabel('B')
l_c = QLabel('C')
l_d = QLabel('D')
l_e = QLabel('E')
l_f = QLabel('F')
l_g = QLabel('G')
l_h = QLabel('H')
l_i = QLabel('I')
self.split_H1 = QSplitter(Qt.Horizontal)
self.split_H1.addWidget(l_a)
self.split_H1.addWidget(l_b)
self.split_H1.addWidget(l_c)
self.split_V.addWidget(self.split_H1)
self.split_H2 = QSplitter(Qt.Horizontal)
self.split_H2.addWidget(l_d)
self.split_H2.addWidget(l_e)
self.split_H2.addWidget(l_f)
self.split_V.addWidget(self.split_H2)
self.split_H3 = QSplitter(Qt.Horizontal)
self.split_H3.addWidget(l_g)
self.split_H3.addWidget(l_h)
self.split_H3.addWidget(l_i)
self.split_V.addWidget(self.split_H3)
self.globallayout.addWidget(self.split_V)
self.wid.setLayout(self.globallayout)
self.split_H1.splitterMoved.connect(self.moveSplitter)
self.split_H2.splitterMoved.connect(self.moveSplitter)
self.split_H3.splitterMoved.connect(self.moveSplitter)
# self.split_H1.splitterMoved
# self.moveSplitter(0,self.split_H1.at )
def moveSplitter( self, index, pos ):
# splt = self._spltA if self.sender() == self._spltB else self._spltB
self.split_H1.blockSignals(True)
self.split_H2.blockSignals(True)
self.split_H3.blockSignals(True)
self.split_H1.moveSplitter(index, pos)
self.split_H2.moveSplitter(index, pos)
self.split_H3.moveSplitter(index, pos)
self.split_H1.blockSignals(False)
self.split_H2.blockSignals(False)
self.split_H3.blockSignals(False)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
ex.show()
sys.exit(app.exec_( ))
However, I still have an issue at the begining - the alignment is not correct :
I don't know How call the function moveSplitter in the __init__
It seems that directly calling moveSplitter (which is a protected method) may be problematic. Using Qt-5.10.1 with PyQt-5.10.1 on Linux, I found that it can often result in a core dump when called during __init__. There is probably a good reason why Qt provides setSizes as a public method for changing the position of the splitters, so it may be wise to prefer it over moveSplitter.
With that in mind, I arrived at the following implementation:
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
...
self.split_H1.splitterMoved.connect(self.moveSplitter)
self.split_H2.splitterMoved.connect(self.moveSplitter)
self.split_H3.splitterMoved.connect(self.moveSplitter)
QTimer.singleShot(0, lambda: self.split_H1.splitterMoved.emit(0, 0))
def moveSplitter(self, index, pos):
sizes = self.sender().sizes()
for index in range(self.split_V.count()):
self.split_V.widget(index).setSizes(sizes)
The single-shot timer is needed because on some platforms the geometry of the window may not be fully initialized before it is shown on screen. And note that setSizes does not trigger splitterMoved, so there is no need to block signals when using it.

Scrolling Text in PyQt?

I'm trying to have text from feedparser scroll across the screen from right to left. I'm using PyQt5, I'm not sure how to go about adding this feature.
What I want to display is below
import feedparser
sports = feedparser.parse('http://rssfeeds.usatoday.com/UsatodaycomSports-TopStories')
for e in sports['entries']:
news = (e.get('title', ''))
I'm looking for a continuous scrolling until all the news headlines are read and then the page is reloaded to get the most recent headlines or just reread whats already there. Thanks!
You can use QTimeLine to show a continously scrolling slice of the news in a label. I implemented it in a little gui to try, if other functions in the app are blocked while QTimeLine is running:
import feedparser
import sys
from PyQt5 import QtWidgets, QtCore
class MyWidget(QtWidgets.QWidget):
def __init__(self, parent = None):
QtWidgets.QWidget.__init__(self, parent)
self.setGeometry(200, 200, 800, 600)
self.textLabel = QtWidgets.QLabel('') # label showing some text
self.uButton = QtWidgets.QPushButton('upper Button')
self.lButton = QtWidgets.QPushButton('lower Button')
self.label = QtWidgets.QLabel('') # label showing the news
self.label.setAlignment(QtCore.Qt.AlignRight) # text starts on the right
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.textLabel)
self.layout.addWidget(self.uButton)
self.layout.addWidget(self.lButton)
self.layout.addWidget(self.label)
self.layout.setStretch(0, 3)
self.layout.setStretch(1, 3)
self.layout.setStretch(2, 3)
self.layout.setStretch(3, 1)
self.setLayout(self.layout)
self.timeLine = QtCore.QTimeLine()
self.timeLine.setCurveShape(QtCore.QTimeLine.LinearCurve) # linear Timeline
self.timeLine.frameChanged.connect(self.setText)
self.timeLine.finished.connect(self.nextNews)
self.signalMapper = QtCore.QSignalMapper(self)
self.signalMapper.mapped[str].connect(self.setTlText)
self.uButton.clicked.connect(self.signalMapper.map)
self.signalMapper.setMapping(self.uButton, self.uButton.text())
self.lButton.clicked.connect(self.signalMapper.map)
self.signalMapper.setMapping(self.lButton, self.lButton.text())
self.feed()
def feed(self):
fm = self.label.fontMetrics()
self.nl = int(self.label.width()/fm.averageCharWidth()) # shown stringlength
news = []
sports = feedparser.parse('http://rssfeeds.usatoday.com/UsatodaycomSports-TopStories')
for e in sports['entries']:
news.append(e.get('title', ''))
appendix = ' '*self.nl # add some spaces at the end
news.append(appendix)
delimiter = ' +++ ' # shown between the messages
self.news = delimiter.join(news)
newsLength = len(self.news) # number of letters in news = frameRange
lps = 4 # letters per second
dur = newsLength*1000/lps # duration until the whole string is shown in milliseconds
self.timeLine.setDuration(dur)
self.timeLine.setFrameRange(0, newsLength)
self.timeLine.start()
def setText(self, number_of_frame):
if number_of_frame < self.nl:
start = 0
else:
start = number_of_frame - self.nl
text = '{}'.format(self.news[start:number_of_frame])
self.label.setText(text)
def nextNews(self):
self.feed() # start again
def setTlText(self, text):
string = '{} pressed'.format(text)
self.textLabel.setText(string)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
Add PySide2 version:
import feedparser
import sys
from PySide2 import QtWidgets, QtCore
class MyWidget(QtWidgets.QWidget):
def __init__(self, parent = None):
QtWidgets.QWidget.__init__(self, parent)
self.setGeometry(200, 200, 800, 600)
self.textLabel = QtWidgets.QLabel('') # label showing some text
self.uButton = QtWidgets.QPushButton('upper Button')
self.lButton = QtWidgets.QPushButton('lower Button')
self.label = QtWidgets.QLabel('') # label showing the news
self.label.setAlignment(QtCore.Qt.AlignRight) # text starts on the right
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.textLabel)
self.layout.addWidget(self.uButton)
self.layout.addWidget(self.lButton)
self.layout.addWidget(self.label)
self.layout.setStretch(0, 3)
self.layout.setStretch(1, 3)
self.layout.setStretch(2, 3)
self.layout.setStretch(3, 1)
self.setLayout(self.layout)
self.timeLine = QtCore.QTimeLine()
self.timeLine.setCurveShape(QtCore.QTimeLine.LinearCurve) # linear Timeline
self.timeLine.frameChanged.connect(self.setText)
self.timeLine.finished.connect(self.nextNews)
self.signalMapper = QtCore.QSignalMapper(self)
self.signalMapper.mapped[str].connect(self.setTlText)
self.uButton.clicked.connect(self.signalMapper.map)
self.signalMapper.setMapping(self.uButton, self.uButton.text())
self.lButton.clicked.connect(self.signalMapper.map)
self.signalMapper.setMapping(self.lButton, self.lButton.text())
self.feed()
def feed(self):
fm = self.label.fontMetrics()
self.nl = int(self.label.width()/fm.averageCharWidth()) # shown stringlength
news = []
sports = feedparser.parse('http://rssfeeds.usatoday.com/UsatodaycomSports-TopStories')
for e in sports['entries']:
news.append(e.get('title', ''))
appendix = ' '*self.nl # add some spaces at the end
news.append(appendix)
delimiter = ' +++ ' # shown between the messages
self.news = delimiter.join(news)
newsLength = len(self.news) # number of letters in news = frameRange
lps = 4 # letters per second
dur = newsLength*1000/lps # duration until the whole string is shown in milliseconds
self.timeLine.setDuration(dur)
self.timeLine.setFrameRange(0, newsLength)
self.timeLine.start()
def setText(self, number_of_frame):
if number_of_frame < self.nl:
start = 0
else:
start = number_of_frame - self.nl
text = '{}'.format(self.news[start:number_of_frame])
self.label.setText(text)
def nextNews(self):
self.feed() # start again
def setTlText(self, text):
string = '{} pressed'.format(text)
self.textLabel.setText(string)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())

What happens with QMainWindow

I want to create the GUI with this code. When i click Add New Object Button, it will show the pop up (I use QMainWindown) but i want to put the QLabel in here, it can not work
I dont know why.i hope everyone can give me more some advices. Thanks you
This is my code :
from PySide import QtCore, QtGui
import sys
app = QtGui.QApplication.instance()
if not app:
app = QtGui.QApplication([])
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.mainLayout = QtGui.QGridLayout()
self.mainLayout.addWidget(self.First(), 0, 0, 2, 0)
self.setLayout(self.mainLayout)
self.setWindowTitle("Library")
self.resize(700,660)
#----------------------------------------FIRST COLUMN-------------------------------------
def First(self):
FirstFrame = QtGui.QFrame()
FirstFrame.setFixedSize(230,700)
# LABEL
renderer_lb = QtGui.QLabel("Renderer :")
folders_lb = QtGui.QLabel("Folder :")
#COMBOBOX
self.renderer_cbx = QtGui.QComboBox()
self.renderer_cbx.addItem("Vray")
self.renderer_cbx.addItem("Octane")
# LIST VIEW FOLDER
self.folders_lv = QtGui.QListView()
# BUTTON
addnewobject_btn = QtGui.QPushButton("Add New Objects")
newset_btn = QtGui.QPushButton("New Set")
# DEFINE THE FUNCTION FOR FIRST FRAME
Firstbox = QtGui.QGridLayout()
Firstbox.addWidget(renderer_lb,0,0)
Firstbox.addWidget(folders_lb,2,0,1,4)
Firstbox.addWidget(self.renderer_cbx,0,1,1,3)
Firstbox.addWidget(self.folders_lv,3,0,1,4)
Firstbox.addWidget(addnewobject_btn,4,0,1,2)
Firstbox.addWidget(newset_btn,4,3)
Firstbox.setColumnStretch(1, 1)
FirstFrame.setLayout(Firstbox)
addnewobject_btn.clicked.connect(self.addnewobject)
return FirstFrame
def addnewobject(self):
window = QtGui.QMainWindow(self)
window.setWindowTitle('Select folder of new objects')
window.setFixedSize(450,90)
window.show()
folder_lb = QtGui.QLabel("Folder : ")
browser = QtGui.QGridLayout()
browser.addWidget(folder_lb,0,0)
window.setLayout(browser)
if __name__ == '__main__':
window = Window()
sys.exit(window.exec_())
Just as you did in the First() function, you could create an homemade widget using QFrame. Then you can set a central widget for your new window.
from PySide import QtCore, QtGui
import sys
app = QtGui.QApplication.instance()
if not app:
app = QtGui.QApplication([])
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.mainLayout = QtGui.QGridLayout()
self.mainLayout.addWidget(self.First(), 0, 0, 2, 0)
self.setLayout(self.mainLayout)
self.setWindowTitle("Library")
self.resize(700,660)
self.show()
#----------------------------------------FIRST COLUMN-------------------------------------
def First(self):
FirstFrame = QtGui.QFrame()
FirstFrame.setFixedSize(230,700)
# LABEL
renderer_lb = QtGui.QLabel("Renderer :")
folders_lb = QtGui.QLabel("Folder :")
#COMBOBOX
self.renderer_cbx = QtGui.QComboBox()
self.renderer_cbx.addItem("Vray")
self.renderer_cbx.addItem("Octane")
# LIST VIEW FOLDER
self.folders_lv = QtGui.QListView()
# BUTTON
addnewobject_btn = QtGui.QPushButton("Add New Objects")
newset_btn = QtGui.QPushButton("New Set")
# DEFINE THE FUNCTION FOR FIRST FRAME
Firstbox = QtGui.QGridLayout()
Firstbox.addWidget(renderer_lb,0,0)
Firstbox.addWidget(folders_lb,2,0,1,4)
Firstbox.addWidget(self.renderer_cbx,0,1,1,3)
Firstbox.addWidget(self.folders_lv,3,0,1,4)
Firstbox.addWidget(addnewobject_btn,4,0,1,2)
Firstbox.addWidget(newset_btn,4,3)
Firstbox.setColumnStretch(1, 1)
FirstFrame.setLayout(Firstbox)
addnewobject_btn.clicked.connect(self.addnewobject)
return FirstFrame
def addnewobject(self):
secondFrame = QtGui.QFrame()
secondFrame.setFixedSize(230,700)
# LABEL
folders_lb = QtGui.QLabel("Folder :")
# DEFINE THE FUNCTION FOR FIRST FRAME
secondGridLayout = QtGui.QGridLayout()
secondGridLayout.addWidget(folders_lb,2,0,1,4)
secondGridLayout.setColumnStretch(1, 1)
secondFrame.setLayout(secondGridLayout)
window = QtGui.QMainWindow(self)
window.setWindowTitle('Select folder of new objects')
window.setFixedSize(600,700)
window.setCentralWidget(secondFrame) # Here is the main change: setLayout(QLayout) to setCentralWidget(QWidget)
window.show()
if __name__ == '__main__':
window = Window()
sys.exit(window.exec_())
Is this intended for Maya? If yes, I recommand you not to use modal windows as it will quickly fed up the users.

Categories