I've got a PyQt GUI with a QTextEdit in it. I have set a few of the widget settings to play with things like the font size. What I'm seeing is that when I initially type in the field, the settings are applied, but if I delete all text and start typing again, the settings have reset to the default ones. Below is a MWE where I can see this behavior. Just in case it matters, I'm using Python 3.5.1 with PyQt4 4.8.7.
from PyQt4 import QtCore, QtGui
class App(object):
def __init__(self):
self.app = QtGui.QApplication([]) # The main application
self.win = QtGui.QMainWindow() # The main window
self.widget = QtGui.QWidget() # The central widget in the main window
self.grid = QtGui.QVBoxLayout() # The layout manager of the central widget
self.textArea = QtGui.QTextEdit()
self.grid.addWidget(self.textArea)
self.textArea.setMinimumSize(600,300)
self.textArea.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.textArea.setFontPointSize(12)
self.widget.setLayout(self.grid)
self.win.setCentralWidget(self.widget)
self.win.show()
self.app.exec_()
App()
You can create a new QFont item and then you can use QTextEdit.setFont()
This way it will not reset after all text is deleted.
Related
I had an application that contained a lot of widgets with stylesheet on them, However, I did not add any layout to interface, It neither had central widget included, But the application was running without any problems.
However, whenever i tried to resize the application (scaling it down) the widgets would not scale, of course.
I had an little research (Because i could not find anything else related to my problem) and i found this on Qt Documentation, stylesheet reference:
"The actual image that is drawn is determined using the same algorithm as QIcon (i.e) the image is never scaled up but always scaled down if necessary."
How can i make stylesheet scale down with window? (If stylesheet has background image on)
For example i have button with stylesheet:
btn = QtGui.QPushButton(self)
btn.move(0, 0)
btn.setObjectName('btn)
btn.setStyleSheet("#btn {background-image: url(':/images/somepicture.png'); border: none; }")
How can i make this button scale down with window, Can i achieve this without layouts? If not how can i do it with layouts? (without it limiting too much)
If you add the button as the central widget to a QMainWindow it should automatically adjust it's size to fit the available space. However, to get the button image to scale, you need to set the image as a border-image stylesheet property (a little strange). A working example for PyQt4:
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
btn = QtGui.QPushButton(self)
btn.setStyleSheet("border-image: url('somepicture.png');") # Scaled
#btn.setStyleSheet("background-image: url('somepicture.png');") # Not scaled
self.setCentralWidget(btn)
self.show()
app = QtGui.QApplication([])
window = MainWindow()
app.exec_()
Note that you don't need to set an id (objectName) to assign the CSS to a specific widget, you can simply pass in the CSS rule via .setStyleSheet().
You cannot set a layout on QMainWindow as it already has a complex layout system to accommodate docking widgets and toolbars. Therefore, if you want to use a layout to add more than one widget to the window, you need to use a container widget to hold it. The following working example demonstrates this:
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
w = QtGui.QWidget() # container widget
l = QtGui.QVBoxLayout() # your layout
w.setLayout(l) # set the layout on your container widget
btn = QtGui.QPushButton(self)
btn.setStyleSheet("border-image: url('somepicture.png');")
label = QtGui.QLabel('Hello!')
l.addWidget(btn) # add your widget to the layout
l.addWidget(label) # add the label to the layout
self.setCentralWidget(w) # add the container widget to the QMainWindow
self.show()
app = QtGui.QApplication([])
window = MainWindow()
app.exec_()
If you want to be able to position widgets absolutely, rather than adding them to a layout (which will control their size/position) you can pass the parent element (relative to which x,y coords are taken) when creating it:
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
w = QtGui.QWidget() # container widget
btn = QtGui.QPushButton(w)
btn.move(100,100)
btn.setStyleSheet("border-image: url('somepicture.png');")
self.setCentralWidget(w) # add the container widget to the QMainWindow
self.show()
app = QtGui.QApplication([])
window = MainWindow()
app.exec_()
But positioning a widget absolutely like this loses you the ability to auto-scale it to fit the parent widget. If you just want some padding/spacing around the element in the window, take a look at .setContentsMargins on the QLayouts, e.g. l.setContentsMargins(50,50,50,50) will put a 50px margin around the button.
Disclaimer: New to both python and qt designer
QT Designer 4.8.7
Python 3.4
PyCharm 5.0.3
Question - How do I add controls to the main form or a scroll area widget on the main form (created in QT Designer) programmatically?
I have created a MainWindow in qt designer and added my widgets. The following is the entire test program in PyCharm:
import sys
from PyQt4 import QtGui, QtCore, uic
from PyQt4.QtGui import *
from PyQt4.QtCore import *
qtCreatorFile = "programLauncher.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
# Cannot resize or maximize
self.setFixedSize(1045, 770)
# Add button test
self.dateLabel = QtGui.QLabel("Test")
self.pushButton = QtGui.QPushButton('Test button')
# self.scrollArea_programs.addWidget()
grid = QtGui.QGridLayout()
# self.scrollArea_programs.addWidget(self.pushButton)
grid.addWidget(self.dateLabel,0,0)
grid.addWidget(self.pushButton,0,1)
self.setLayout(grid)
self.pushButton_exit.clicked.connect(self.closeEvent)
def closeEvent(self):
QtGui.QApplication.quit()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
As you can see I tried to add controls to a grid but nothing shows up when the program runs - I have also tried to add a control to the scroll area. Can someone help me to just add 1 control to the scroll area at run time - so then I can know the proper way to do it or "a" proper way to do this.
Thanks in advance
Without having access to your programLauncher.ui and making minimal changes to your posted code, you can add your UI elements to the window like so:
from PyQt4 import QtGui
import sys
class MyApp(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# Cannot resize or maximize
self.setFixedSize(1045, 770)
widget = QtGui.QWidget(self)
self.setCentralWidget(widget)
# Add button test
self.dateLabel = QtGui.QLabel("Test")
self.pushButton = QtGui.QPushButton('Test button')
grid = QtGui.QGridLayout()
grid.addWidget(self.dateLabel, 0, 0)
grid.addWidget(self.pushButton, 0, 1)
widget.setLayout(grid)
self.pushButton.clicked.connect(self.closeEvent)
def closeEvent(self, event):
QtGui.QApplication.quit()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
This will get the controls on the screen, although the layout leaves a lot to be desired. You may have to make modifications to this based on what's in your .ui file. One thing that you'll want to note in this example is that the QMainWindow needs a central widget (widget in the example above). You then set the layout on that widget.
You can use the designer to create your .ui file
The you can load it in your .py using something like:
from PyQt4 import QtCore, QtGui, uic
class my_win(QtGui.QMainWindow):
def __init__(self):
self.ui = uic.loadUi('my_ui.ui',self)
then you can access all your widgets with something like
self.ui.actionQuit.triggered.connect(QtGui.qApp.quit)
or
self.ui.my_button.triggered.connect(self.do_someting)
Thanks to JCVanHamme (the programLauncher.ui hint) and also outside help I now learned most of what I need to know to access MainWindow at run time. So for anyone interested in this beginner tip:
Take a blank form in QT Designer
Add a control
Run pyuic4 batch file
Take a look at the generated .py file to learn EVERYTHING about how to add controls.
Don't let the power go to your head - cheers
I want to implement a GUI program like the blueprint editor in the Unreal game engine with PyQt4. Here is an example of the blueprint editor:
First I create a simple container widget to place all the components(The rectangles). In order to allow the user place the rectangles wherever they want(by drag & drop), I can't place my widgets in a layout. Then when the content of the rectangle is changed, the rectangle widget can't auto adjust the size itself.
Following is an example code:
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
class ChangeableChild(QtGui.QWidget):
def __init__(self, parent=None):
super(ChangeableChild, self).__init__(parent)
self.setLayout(QtGui.QVBoxLayout())
def addWidget(self, widget):
self.layout().addWidget(widget)
class MainWidget(QtGui.QWidget):
def __init__(self, child, parent=None):
super(MainWidget, self).__init__(parent)
child.setParent(self)
def main():
app = QtGui.QApplication(sys.argv)
changeable_child = ChangeableChild()
button = QtGui.QPushButton("Add label")
changeable_child.addWidget(button)
win = MainWidget(changeable_child)
win.show()
button.clicked.connect(
lambda: changeable_child.addWidget(QtGui.QLabel("A label.")))
app.exec_()
if __name__ == "__main__":
main()
When I hit "Add label" button to add a new label. The size of ChangeableChild wouldn't change automatically. If I put the ChangeableChild in a layout, it's all good.
So is there a way to auto adjust my widget when it's not in a layout? Or is there a way I can place my widget in a layout and still can place it in a absolute position?
in my Qt application I have a plainTextEdit box into which I expect the user to enter the serial number of the hardware for which he wants the python/Qt application to generate a report. So, the HW Serial Number is a must input for my application, if he doesn't enter that then I don't want to enable the Report Generate pushButton.
How can I detect that he has entered some text in the box? Then enable the button?
How to detect if he completely erases what he has entered? Then disable the button?
Connect to the textChanged() signal of QPlainTextEdit. This will be fired whenever the text changes. You can then access the contents of the QPlainTextEdit through toPlainText() and use it to decide whether to enable or disable the button.
Here's a simple example:
import sys
from PySide import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
widget = QtGui.QWidget()
self.edit = QtGui.QPlainTextEdit()
QtCore.QObject.connect(self.edit, QtCore.SIGNAL('textChanged()'), self.handleTextChange)
self.button = QtGui.QPushButton('Generate Report')
self.button.setEnabled(False)
layout = QtGui.QVBoxLayout(widget)
layout.addWidget(self.edit)
layout.addWidget(self.button)
self.setCentralWidget(widget)
#QtCore.Slot()
def handleTextChange(self):
self.button.setDisabled(self.edit.toPlainText() == '')
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
I have a problem to set a new layout in my QWidget object. I start to set one type of layout when the app exec, and I want to change it when the button is pressed with a new layout. In the documentation of PySide I read this:
Sets the layout manager for this widget to layout.
If there already is a layout manager installed on this widget,
PySide.QtGui.QWidget won’t let you install another. You must first
delete the existing layout manager (returned by
PySide.QtGui.QWidget.layout() ) before you can call
PySide.QtGui.QWidget.setLayout() with the new layout.
But how can I delete the existing layout manager? What are the methods which I must apply on my QWidget object?
If you're new to PySide/PyQt, see the Layout Management article in the documentation for an overview of Qt's layout system.
For your specific example, you will need a method to recursively remove and delete all the objects from a layout (i.e. all its child widgets, spacer-items and other layouts). And also a method to build and add the new layout.
Here's a simple demo:
from PySide import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.changeLayout(QtCore.Qt.Vertical)
self.button = QtGui.QPushButton('Horizontal', self)
self.button.clicked.connect(self.handleButton)
layout.addStretch()
layout.addWidget(self.button)
def handleButton(self):
if self.button.text() == 'Horizontal':
self.changeLayout(QtCore.Qt.Horizontal)
self.button.setText('Vertical')
else:
self.changeLayout(QtCore.Qt.Vertical)
self.button.setText('Horizontal')
def changeLayout(self, direction):
if self.layout().count():
layout = self.layout().takeAt(0)
self.clearLayout(layout)
layout.deleteLater()
if direction == QtCore.Qt.Vertical:
layout = QtGui.QVBoxLayout()
else:
layout = QtGui.QHBoxLayout()
for index in range(3):
layout.addWidget(QtGui.QLineEdit(self))
self.layout().insertLayout(0, layout)
def clearLayout(self, layout):
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
self.clearLayout(item.layout())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 300, 100)
window.show()
sys.exit(app.exec_())