PySide how to toggle visibility of QTextBrowser - python

I want to show/hide QTextBrowser widget by pressing a single button. Is there any mean to toggle it? Now I have two buttons; one for displaying the textbrowser and another for hiding it. Buttons are also hided depending on the visibility of the textbrowser. This implementation works as expected, but I think there should/must be a more sophisticated way to implement it. Any suggestions?
def __init__(self, parent=None):
super(Program, self).__init__(parent)
...code...
self.connect(self.showDetailsButton, SIGNAL("clicked()"), self.showTextBrowser)
self.textBrowser.hide() #hide the textbrowser by default
self.resize(461, 200)
self.connect(self.hideDetailsButton, SIGNAL("clicked()"), self.hideTextBrowser)
self.hideDetailsButton.hide() #hide the hideDetailsButton by default
...code...
def showTextBrowser(self):
self.textBrowser.show()
self.hideDetailsButton.show()
self.showDetailsButton.hide()
self.resize(461, 444)
def hideTextBrowser(self):
self.textBrowser.hide()
self.showDetailsButton.show()
self.hideDetailsButton.hide()
self.resize(461, 200)
...code...
Dialog is resized whenever the QTextBrowser widget is shown or hided.

You only need one button, and one handler. Change the text of the button when it's clicked, and use the current visibility of the browser to toggle between the two states.
Here's a working demo:
from PySide import QtCore, QtGui
class Program(QtGui.QWidget):
def __init__(self):
super(Program, self).__init__()
self.textBrowser = QtGui.QTextBrowser(self)
self.button = QtGui.QPushButton('Hide', self)
self.button.clicked.connect(self.toggleTextBrowser)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.textBrowser)
layout.addWidget(self.button)
def toggleTextBrowser(self):
if self.textBrowser.isHidden():
self.button.setText('Hide')
self.textBrowser.show()
self.resize(461, 444)
else:
self.button.setText('Show')
self.textBrowser.hide()
self.resize(461, 200)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Program()
window.setGeometry(500, 300, 461, 444)
window.show()
sys.exit(app.exec_())

Just save the current state and use it to toggle the visibility:
def toggleVisibleTextBrowser(self):
isVisible= !isVisible # declared somewhere else
self.textBrowser.setVisible(isVisible)
if isVisible:
self.resize(461, 444)
else
self.resize(461, 200)
...

Related

adding QWidgets to scrollArea causes them to pile up on top of eachother

I'm somewhat experienced in python but it's been a looooong time so bear with me on this.
Okay, so I found this really great PyQt code sample where a guy pushes buttons onto a scroll area, which automatically triggers a scrollbar when the content (the buttons) overflow.
So I went and tried to do the very same thing but pushing widgets to the scroll area, this is my code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui
class myDialog(QtGui.QWidget):
_buttons = 0
def __init__(self, parent=None):
super(myDialog, self).__init__(parent)
self.setGeometry(50, 50, 500, 500)
self.pushButton = QtGui.QPushButton(self)
self.pushButton.setText(QtGui.QApplication.translate("self", "Add Button!", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.scrollArea = QtGui.QScrollArea(self)
self.scrollArea.setWidgetResizable(True)
self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout = QtGui.QVBoxLayout(self)
self.verticalLayout.addWidget(self.pushButton)
self.verticalLayout.addWidget(self.scrollArea)
self.verticalLayoutScroll = QtGui.QVBoxLayout(self.scrollAreaWidgetContents)
#QtCore.pyqtSlot()
def on_pushButton_clicked(self):
self._buttons += 1
pustButtonName = u"Button {0}".format(self._buttons)
#pushButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
#pushButton.setText(pustButtonName)
muhAlarma = AlarmaWidget(self.scrollAreaWidgetContents)
self.verticalLayoutScroll.addWidget(muhAlarma)
class AlarmaWidget(QtGui.QWidget):
def __init__(self, parent):
super(AlarmaWidget, self).__init__(parent)
#self.setGeometry(0,0, 30, 30)
theButton = QtGui.QPushButton(self)
theButton.setText("It's Friday my dudes.")
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
main = myDialog()
#main.setWindowFlags(QtCore.Qt.FramelessWindowHint)
#main.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
#main.showFullScreen()
main.show()
sys.exit(app.exec_())
Upon running this code and pressing the button, buttons will start to appear.
However, the big problem is that instead of filling up the scrollbar area and causing the scrollbar to be enabled, the buttons just end up piling on top of each other, why is that?
PS: uncommenting the commented pushButton lines and commenting the muhAlarma line will make this sample work again. However I need to push custom widgets, not buttons.
Thanks in advance
Adding QWidgets (QPushButton) to scrollArea.
This is the example code for insert QWidgets (QPushButton) to scrollArea.
Please check this code. Are you expecting this result,
If your are not expecting this answer, sorry.
Thanks, Subin
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class myDialog (QtGui.QWidget):
def __init__(self, parent=None):
super(myDialog, self).__init__(parent)
self.button = QtGui.QPushButton (self)
self.button.setObjectName ('button')
self.button.setText ('Add Button')
self.scrollArea = QtGui.QScrollArea (self)
self.scrollArea.setWidgetResizable (True)
self.scrollArea.setObjectName('scrollArea')
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setObjectName('scrollAreaWidgetContents')
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout = QtGui.QVBoxLayout (self)
self.verticalLayout.setObjectName ('verticalLayout')
self.verticalLayout.addWidget(self.button)
self.verticalLayout.addWidget (self.scrollArea)
self.verticalLayout_scroll = QtGui.QVBoxLayout (self.scrollAreaWidgetContents)
self.verticalLayout_scroll.setObjectName ('verticalLayout_scroll')
self.button.clicked.connect (self.createButtons)
self.resize(250, 330)
def createButtons (self) :
existsButtonList = []
for loop in range (self.verticalLayout_scroll.count ()) :
if type(self.verticalLayout_scroll.itemAt(loop).widget())==QtGui.QPushButton :
existsButtonList.append (self.verticalLayout_scroll.itemAt(loop).widget())
button_custom = QtGui.QPushButton (self)
button_custom.setObjectName ('button%s'% str(len(existsButtonList)+1))
button_custom.setText ('Add Button - %s'% str(len(existsButtonList)+1))
self.verticalLayout_scroll.addWidget(button_custom)
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
widget = myDialog ()
widget.show()
app.exec_()
Okay I have found a solution after almost going crazy for quite a while.
If anyone is having a similar problem, I've got your back!
in
AlarmaWidget.__init__
set a minimunHeight like so:
self.setMinimumHeight(50)

How can I make a PyQt widget resizable by dragging?

I have a QScrollArea containing a widget with a QVBoxLayout. Inside this layout are several other widgets. I want the user to be able to drag the lower borders of those widgets to resize them in the vertical direction. When they are resized, I don't want them to "steal" size from the other widgets in the scrolling area; instead I want the entire scrolled "page" to change its size. So if you enlarge one of the widgets, it should push the other widgets down (out of the viewport of the scroll area); if you shrink it, it should pull the other widgets up. Dragging the border of one widget should not change the size of any of the other widgets in the vertical scroll; it should just move them.
I began by using a QSplitter. If I use that, I can drag to change the size of a widget, but there doesn't seem to be a way to get it to "push/pull" the others as I described above, rather than growing/shrinking them. But I can't find any other way to give a widget a draggable handle that will allow me to change its size. How can I accomplish this?
Here is a simple example of what I'm doing. (In this example I've commented out the splitter, but if you uncomment it you can see what happens with that version.)
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.Qsci import QsciScintilla, QsciLexerPython
class SimplePythonEditor(QsciScintilla):
def __init__(self, parent=None):
super(SimplePythonEditor, self).__init__(parent)
self.setMinimumHeight(50)
class Chunk(QFrame):
def __init__(self, parent=None):
super(Chunk, self).__init__(parent)
layout = QVBoxLayout(self)
sash = QSplitter(self)
layout.addWidget(sash)
sash.setOrientation(Qt.Vertical)
editor = self.editor = SimplePythonEditor()
output = self.output = SimplePythonEditor()
output.setReadOnly(True)
sash.addWidget(editor)
sash.addWidget(output)
self.setLayout(layout)
print(self.sizePolicy())
class Widget(QWidget):
def __init__(self, parent= None):
global inout
super(Widget, self).__init__()
#Container Widget
widget = QWidget()
#Layout of Container Widget
layout = QVBoxLayout(self)
#sash = QSplitter(self)
#layout.addWidget(sash)
#sash.setOrientation(Qt.Vertical)
for num in range(5):
editor = SimplePythonEditor()
editor.setText("Some stuff {}".format(num))
layout.addWidget(editor)
#sash.addWidget(editor)
widget.setLayout(layout)
#Scroll Area Properties
scroll = QScrollArea()
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll.setWidgetResizable(True)
scroll.setWidget(widget)
scroll.setMaximumHeight(500)
#Scroll Area Layer add
vLayout = QVBoxLayout(self)
vLayout.addWidget(scroll)
self.setLayout(vLayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = Widget()
dialog.show()
app.exec_()
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowTitle("MainWindow")
MainWindow.resize(500, 500)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
QMetaObject.connectSlotsByName(MainWindow)
class Ewindow(QMainWindow,QApplication):
"""docstring for App"""
resized = pyqtSignal()
def __init__(self,parent):
super(Ewindow,self).__init__(parent=parent)
self.setGeometry(500, 500, 800,800)
self.setWindowTitle('Mocker')
self.setWindowIcon(QIcon('icon.png'))
self.setAttribute(Qt.WA_DeleteOnClose)
ui2 = Ui_MainWindow()
ui2.setupUi(self)
self.resized.connect(self.readjust)
def resizeEvent(self, event):
self.resized.emit()
return super(Ewindow, self).resizeEvent(event)
def readjust(self):
self.examForm.move(self.width()-self.examForm.width(),0)
self.btn_skip.move(self.width()-self.btn_skip.width(),self.height()-100)
self.btn_next.move(self.btn_showAnswers.x()+self.btn_showAnswers.width(),self.height()-100)
self.btn_prev.move(0,self.height()-100)
self.btn_showAnswers.move(self.btn_prev.x()+self.btn_prev.width(),self.height()-100)
self.btn_home.move(self.width()-200,self.height()-150)
self.lbscreen1.resize(self.width()-self.examForm.width(),self.height()-200)
self.examForm.resize(200,self.height()-150)
self.btn_skip.resize(self.examForm.width(),100)
self.btn_next.resize(self.btn_prev.width(),100)
self.btn_prev.resize(self.width()*0.25,100)
self.btn_showAnswers.resize(self.btn_prev.width(),100)
self.btn_home.resize(200,50)
here is an example code of a resizable window it moves and stretches widgets as you resize the window. The idea is to keep widget coordinates and sizes relative to each other.
so i had to make a class Ui_MainWindow and set it for my window class ui2.setupUi(self) and also declare the resized = pyqtSignal() which i'd be using to run the readjust function which resets size and coordinates of the widgets like so self.resized.connect(self.readjust).
i hope this helps!

How to add a second pixmap to an abstract button when pushed in PySide/PyQt

I'm very new to PySide/PyQt environment. I'm trying to make a menu of buttons on top and assign a task to each so that when they are clicked a function draws a painting on the central window. But I also want to make the button change when they are clicked.
I think this might be an straighforward problem to solve if I use QPushButton, but my buttons are images and I'm using the method suggested HERE and use QAbstractButton to create them.
It is mentioned there that
You can add second pixmap and draw it only when the mouse pointer is
hover over button.
And I'm trying to do exactly that. My question is this:
what are possible ways to achieve this? Are the same methods in QPushButtons applicable here? If so, are there any examples of it somewhere?
Here is a snippet of my code:
import sys
from PySide import QtGui, QtCore
BACKGROUND_COLOR = '#808080'
ICON_PATH_ACTIVE = 'icons/activ'
ICON_PATH_PASSIVE = 'icons/pasiv'
class MainWindow(QtGui.QMainWindow):
def __init__(self, app=None):
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
dockwidget = QtGui.QWidget()
self.setGeometry(200, 200, 400, 300)
hbox = QtGui.QHBoxLayout()
1_button = PicButton(QtGui.QPixmap("icons/pasiv/1.png"))
2_button = PicButton(QtGui.QPixmap("icons/pasiv/2.png"))
3_button = PicButton(QtGui.QPixmap("icons/pasiv/3.png"))
hbox.addWidget(1_button)
hbox.addWidget(2_button)
hbox.addWidget(3_button)
vbox = QtGui.QVBoxLayout()
vbox.addLayout(hbox)
vbox.setAlignment(hbox, QtCore.Qt.AlignTop)
dockwidget.setLayout(vbox)
self.setCentralWidget(dockwidget)
class PicButton(QtGui.QAbstractButton):
def __init__(self, pixmap, parent=None):
super(PicButton, self).__init__(parent)
self.pixmap = pixmap
self.setFixedSize(100, 100)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(event.rect(), self.pixmap)
def main():
app = QtGui.QApplication(sys.argv)
central = MainWindow()
central.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Thank you.
Use a regular QPushButton with an icon.
iplay = QtGui.QIcon("path/play_icon.png")
ipause = QtGui.QIcon("path/pause_icon.png")
btn = QtGui.QPushButton(ipause, "", None)
def toggle_play():
if btn.icon() == ipause:
btn.setIcon(iplay)
# Do Pause Action
else:
btn.setIcon(ipause)
# Do Play Action
btn.clicked.connect(toggle_play)
btn.show()
If you want hover functionality then you will have to subclass the QPushButton
class MyButton(QtGui.QPushButton):
custom_click_signal = QtCore.Signal()
def enterEvent(self, event):
super().enterEvent(event)
# Change icon hove image here
def leaveEvent(self, event):
super().leaveEvent(event)
# Change icon back to original image here.
def mousePressEvent(self, event):
super().mousePressEvent(event)
self.custom_click_signal.emit()
# connect to signal btn.custom_click_signal.connect(method)
Icons are probably the easiest way instead of manually managing the paint event. There are also mousePressEvent and mouseReleaseEvents if you want the icon to change for someone holding the button down.

PyQt QVBoxLayout and missing widgets?

I am trying to set up a window that has a text input & a combo box. At the moment I just want to see the text & the selection displayed under the appropriate widget.
I have used QVBoxLayout() as I will be adding more stuff later & thought it would be a simple way of laying out the window.
Unfortunately only the combo box ever gets displayed. The code:
from PyQt4 import QtCore, QtGui
import sys
class Polyhedra(QtGui.QMainWindow):
def __init__(self):
super(Polyhedra, self).__init__()
self.initUI()
def initUI(self):
# Poly names
self.pNames = QtGui.QLabel(self)
polyNameInput = QtGui.QLineEdit(self)
# polyName entry
polyNameInput.textChanged[str].connect(self.onChanged)
# Polytype selection
self.defaultPolyType = QtGui.QLabel("Random polyhedra", self)
polyType = QtGui.QComboBox(self)
polyType.addItem("Random polyhedra")
polyType.addItem("Spheres")
polyType.addItem("Waterman polyhedra")
polyType.activated[str].connect(self.onActivated)
# Layout
vbox = QtGui.QVBoxLayout()
vbox.addWidget(polyNameInput)
vbox.addWidget(self.pNames)
vbox.addWidget(polyType)
vbox.addWidget(self.defaultPolyType)
vbox.addStretch()
# Set up window
self.setGeometry(500, 500, 300, 300)
self.setWindowTitle('Pyticle')
self.show()
# Combo box
def onActivated(self, text):
self.defaultPolyType.setText(text)
self.defaultPolyType.adjustSize()
# Poly names
def onChanged(self, text):
self.pNames.setText(text)
self.pNames.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Polyhedra()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
So whats going on here? Am I missing some important directive to QVBoxLayout()?
Using Python 2.7 on Win 7 x64 machine with PyQt 4.
EDIT: Additional problem (still related to missing widgets)
I have amended the code following the clarification below. I then added more widgets when a certain option in the combobox is chosen (see below) but these widgets dont show. I attempted to add a child widget to 'widget' called 'ranPolyWidget' to take a numerical input.
# Combo box
def onActivated(self, text):
if text=="Random polyhedra":
self.randomSeedLbl = QtGui.QLabel("Seed: ", self)
randomSeed = QtGui.QLineEdit(self)
randomSeed.textChanged[str].connect(self.setSeed)
ranPolyWidget = QtGui.QWidget(self.widget)
rbox = QtGui.QVBoxLayout(ranPolyWidget)
rbox.addWidget(randomSeed)
self.layout().addWidget(ranPolyWidget)
self.show()
else:
self.defaultPolyType.setText(text)
self.defaultPolyType.adjustSize()
Same issue as before, no widgets. I am missing something pretty fundamental arent I?
You're forgetting to set it to the widget or main window, so since the QComboBox is the last one made, it's the only one displayed. Basically, everything is added to the layout, but the layout is "free-floating", and so it does not display properly. You need to bind the layout to a QWidget, which I do here. For most widgets, you can can do this by the QtGui.QVBoxLayout(widget) or by widget.setLayout(layout).
Alternatively, if you want multiple layouts on a widget, you can do have a parent layout and then add each child layout to the main layout.
EDIT: This is a better answer:
Make a widget, set layout to widget and set as central widget.
QMainWindow-s don't like you using the builtin layout or overriding it.
widget = QtGui.QWidget()
vbox = QtGui.QVBoxLayout(widget)
self.setCentralWidget(widget)
Old Answer:
self.layout().addLayout(vbox).
This should fix your issue:
Changes I made:
Since QMainWindow already has a layout, add in a widget (28G) and then set the VBoxLayout to the widget and add it to the main window.
from PyQt4 import QtCore, QtGui
import sys
class Polyhedra(QtGui.QMainWindow):
def __init__(self):
super(Polyhedra, self).__init__()
self.initUI()
def initUI(self):
# Poly names
self.pNames = QtGui.QLabel(self)
polyNameInput = QtGui.QLineEdit(self)
# polyName entry
polyNameInput.textChanged[str].connect(self.onChanged)
# Polytype selection
self.defaultPolyType = QtGui.QLabel("Random polyhedra", self)
polyType = QtGui.QComboBox(self)
polyType.addItem("Random polyhedra")
polyType.addItem("Spheres")
polyType.addItem("Waterman polyhedra")
polyType.activated[str].connect(self.onActivated)
# Layout
widget = QtGui.QWidget()
vbox = QtGui.QVBoxLayout(widget)
vbox.addWidget(polyNameInput)
vbox.addWidget(self.pNames)
vbox.addWidget(polyType)
vbox.addWidget(self.defaultPolyType)
vbox.addStretch()
# Set up window
self.setGeometry(500, 500, 300, 300)
self.setWindowTitle('Pyticle')
self.layout().addWidget(widget)
self.show()
# Combo box
def onActivated(self, text):
self.defaultPolyType.setText(text)
self.defaultPolyType.adjustSize()
# Poly names
def onChanged(self, text):
self.pNames.setText(text)
self.pNames.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Polyhedra()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
EDIT:
For adding new widgets, you should add them to the layout of the central widget and parent them to that widget.
Here's how I'd restructure your full code:
from PyQt4 import QtCore, QtGui
import sys
class CentralWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(CentralWidget, self).__init__(parent)
# set layouts
self.layout = QtGui.QVBoxLayout(self)
# Poly names
self.pNames = QtGui.QLabel(self)
polyNameInput = QtGui.QLineEdit(self)
# polyName entry
polyNameInput.textChanged[str].connect(self.onChanged)
# Polytype selection
self.defaultPolyType = QtGui.QLabel("Random polyhedra", self)
polyType = QtGui.QComboBox(self)
polyType.addItem("Random polyhedra")
polyType.addItem("Spheres")
polyType.addItem("Waterman polyhedra")
polyType.activated[str].connect(self.onActivated)
self.layout.addWidget(polyNameInput)
self.layout.addWidget(self.pNames)
self.layout.addWidget(polyType)
self.layout.addWidget(self.defaultPolyType)
self.layout.addStretch()
def onActivated(self, text):
'''Adds randSeed to layout'''
if text=="Random polyhedra":
self.randomSeedLbl = QtGui.QLabel("Seed: ", self)
randomSeed = QtGui.QLineEdit(self)
randomSeed.textChanged[str].connect(self.setSeed)
self.layout.addWidget(randomSeed)
else:
self.defaultPolyType.setText(text)
self.defaultPolyType.adjustSize()
# Poly names
def onChanged(self, text):
self.pNames.setText(text)
self.pNames.adjustSize()
class Polyhedra(QtGui.QMainWindow):
def __init__(self):
super(Polyhedra, self).__init__()
# I like having class attributes bound in __init__
# Not very Qt of me, but it's more
# so I break everything down into subclasses
# find it more Pythonic and easier to debug: parent->child
# is easy when I need to repaint or delete child widgets
self.central_widget = CentralWidget(self)
self.setCentralWidget(self.central_widget)
# Set up window
self.setGeometry(500, 500, 300, 300)
self.setWindowTitle('Pyticle')
self.show()
# Combo box
def onActivated(self, text):
'''Pass to child'''
self.central_widget.onActivated(text)
def main():
app = QtGui.QApplication(sys.argv)
ex = Polyhedra()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

PyQt : Prevent a window to be opened several times

I made the simple code below as example. It justs open a new window clicking on a button. I don't find a way to prevent this widget to be re-opened if it is already on the screen. I would like to open a QDialog warning if the window already exists and mainly to have the closeEvent method sending a signal to Mainwidget saying that the new window has been closed. This would allow to open the newWidget again.
import sys
from PyQt4 import QtCore, QtGui
class NewWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(NewWidget,self).__init__(parent)
self.lineEdit = QtGui.QLineEdit('new window',self)
self.resize(200,50)
self.show()
def closeEvent(self,ev):
self.Exit = QtGui.QMessageBox.question(self,
"Confirm Exit...",
"Are you sure you want to exit ?",
QtGui.QMessageBox.Yes| QtGui.QMessageBox.No)
ev.ignore()
if self.Exit == QtGui.QMessageBox.Yes:
ev.accept()
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MainWidget,self).__init__(parent)
self.button = QtGui.QPushButton("button", self)
self.button.clicked.connect(self.open_new)
def open_new(self):
self.new = NewWidget()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main = MainWidget()
main.resize(200,50)
main.move(app.desktop().screen().rect().center() - main.rect().center())
main.show()
sys.exit(app.exec_())
I think a better solution is to avoid creating a new window every time you click the button.
One way to do this would be to change the subwindow to a QDialog:
class NewWidget(QtGui.QDialog):
...
and move the resize/show lines into the open_new method:
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
...
self._subwindow = None
def open_new(self):
if self._subwindow is None:
self._subwindow = NewWidget(self)
self._subwindow.resize(200, 50)
# move it next to the main window
pos = self.frameGeometry().topLeft()
self._subwindow.move(pos.x() - 250, pos.y())
self._subwindow.show()
self._subwindow.activateWindow()
So now there is only ever one subwindow, which just gets re-activated whenever the button is clicked.
Great. The final solution of my problem looks like this :
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
...
self._subwindow = QtGui.Qdialog()
def open_new(self):
if self.subwindow.isVisible() is False:
self._subwindow = NewWidget(self)
self._subwindow.resize(200, 50)
# move it next to the main window
pos = self.frameGeometry().topLeft()
self._subwindow.move(pos.x() - 250, pos.y())
self._subwindow.show()
self._subwindow.activateWindow()

Categories

Resources