I'm currently trying to make a graphical interface using PyQt5. Everything has been working fine until now (I have some experience in this after all), but I've been struggling with this problem for a few days now and I can't find a solution anywhere.
In my app I display a FigureCanvas from matplotlib (along with various other widgets) where I have a key event connected to a function which picks a point from a mouse click and saves this point in a QTableWidget. However, I want the user to be able to edit the y-value that was picked up using a validator, so I changed the second column from holding a QTableWidgetItem to a QLineEdit widget. Everything works except when I press enter after editing the QLineEdit widget in the table, the focus doesn't change as expected (I set the focus to go back to the canvas but the cell stays active with the cursor blinking).
In the same app I have another QLineEdit widget elsewhere in the layout which works as expected. When I press enter in this box, the function connected to its returnPressed signal sends the focus back to the canvas.
Can anyone please help me figure out what is going on?
Also, I don't understand why the app start up with focus being on the QLineEdit when I explicitly set focus to the canvas while creating the main frame. Do you know how to fix this?
I've stripped back my app to a minimal example pasted below and the behavior remains the same.
Just to summarize:
I click on the canvas and press 'a' which call the function 'add_point'.
I then click a point in the plot which creates a new row in the Widget and sets focus to the second column.
I input whatever float value I want here and press Enter.
The function 'print_val' is then called but the focus doesn't return to the canvas as expected. The cursor stays blinking in the table cell.
When I edit the leftmost QLineEdit (outside the table) and hit Enter, the function 'func' is called and correctly sends the focus back to the canvas.
Why do the two instances of QLineEdit behave differently?
For reference, the output of the function 'print_val' gives me:
TableWidget has focus? False
Cell editor has focus? False
Thanks in advance!
import sys
from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class GraphicInterface(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setWindowTitle('Test')
self._main = QWidget()
self.setCentralWidget(self._main)
# Create Toolbar and Menubar
toolbar = QToolBar()
toolbar.setMovable(False)
toolbar_fontsize = QFont()
toolbar_fontsize.setPointSize(14)
quit_action = QAction("Close", self)
quit_action.setFont(toolbar_fontsize)
quit_action.setStatusTip("Quit the application")
quit_action.triggered.connect(self.close)
quit_action.setShortcut("ctrl+Q")
toolbar.addAction(quit_action)
# =============================================================
# Start Layout:
layout = QHBoxLayout(self._main)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.line_editor = QLineEdit("3")
self.line_editor.setValidator(QIntValidator(1, 100))
self.line_editor.returnPressed.connect(self.func)
layout.addWidget(self.line_editor)
# Create Table for Pixel Identifications:
pixtab_layout = QVBoxLayout()
label_pixtab_header = QLabel("Pixel Table\n")
label_pixtab_header.setAlignment(Qt.AlignCenter)
self.linetable = QTableWidget()
self.linetable.verticalHeader().hide()
self.linetable.setColumnCount(2)
self.linetable.setHorizontalHeaderLabels(["Pixel", "Wavelength"])
self.linetable.setColumnWidth(0, 80)
self.linetable.setColumnWidth(1, 90)
self.linetable.setFixedWidth(180)
pixtab_layout.addWidget(label_pixtab_header)
pixtab_layout.addWidget(self.linetable)
layout.addLayout(pixtab_layout)
# Create Figure Canvas:
right_layout = QVBoxLayout()
self.fig = Figure(figsize=(6, 6))
self.canvas = FigureCanvas(self.fig)
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.canvas.updateGeometry()
self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
right_layout.addWidget(self.canvas)
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
right_layout.addWidget(self.mpl_toolbar)
layout.addLayout(right_layout)
# Plot some random data:
self.ax = self.fig.add_subplot(111)
self.ax.plot([0, 1, 5, 10, 20], [-1, 2, -4, 5, -2])
def on_key_press(self, e):
if e.key == "a":
self.add_point()
def add_point(self):
print("Select point...")
point = self.fig.ginput(1)
x0, _ = point[0]
rowPosition = self.linetable.rowCount()
self.linetable.insertRow(rowPosition)
item = QTableWidgetItem("%.2f" % x0)
item.setFlags(Qt.ItemIsEnabled)
item.setBackground(QColor('lightgray'))
self.linetable.setItem(rowPosition, 0, item)
y_item = QLineEdit("")
y_item.setValidator(QDoubleValidator())
y_item.returnPressed.connect(self.print_val)
self.linetable.setCellWidget(rowPosition, 1, y_item)
self.linetable.cellWidget(rowPosition, 1).setFocus()
def print_val(self):
rowPosition = self.linetable.rowCount()
editor = self.linetable.cellWidget(rowPosition-1, 1)
y_in = float(editor.text())
print(" Table value: %.2f" % y_in)
# and set focus back to canvas:
self.canvas.setFocus()
# Check which widget has focus:
focus_widget = self.focusWidget()
print(focus_widget.__class__)
print("TableWidget has focus? %r" % self.linetable.hasFocus())
print("Cell editor has focus? %r" % editor.hasFocus())
def func(self):
# dome some stuff
print(self.line_editor.text())
# and set focus back to canvas:
self.canvas.setFocus()
if __name__ == '__main__':
# Launch App:
qapp = QApplication(sys.argv)
app = GraphicInterface()
app.show()
qapp.exec_()
If you want to validate the information of a QTableWidget it is not necessary to insert a QLineEdit but use the one created by the delegate and set a QValidator there:
class ValidatorDelegate(QtWidgets.QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = super(ValidatorDelegate, self).createEditor(parent, option, index)
if isinstance(editor, QtWidgets.QLineEdit):
editor.setValidator(QtGui.QDoubleValidator(editor))
return editor
And then open the editor with the edit method of the view, to change the focus you can use the delegate's closeEditor signal:
import sys
from matplotlib.backends.backend_qt5agg import (
FigureCanvas,
NavigationToolbar2QT as NavigationToolbar,
)
from matplotlib.figure import Figure
from PyQt5 import QtCore, QtGui, QtWidgets
class ValidatorDelegate(QtWidgets.QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = super(ValidatorDelegate, self).createEditor(parent, option, index)
if isinstance(editor, QtWidgets.QLineEdit):
editor.setValidator(QtGui.QDoubleValidator(editor))
return editor
class GraphicInterface(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(GraphicInterface, self).__init__(parent)
self.setWindowTitle("Test")
self._main = QtWidgets.QWidget()
self.setCentralWidget(self._main)
# Create Toolbar and Menubar
toolbar = QtWidgets.QToolBar(movable=False)
toolbar_fontsize = QtGui.QFont()
toolbar_fontsize.setPointSize(14)
quit_action = QtWidgets.QAction("Close", self)
quit_action.setFont(toolbar_fontsize)
quit_action.setStatusTip("Quit the application")
quit_action.triggered.connect(self.close)
quit_action.setShortcut("ctrl+Q")
toolbar.addAction(quit_action)
self.line_editor = QtWidgets.QLineEdit("3")
self.line_editor.setValidator(QtGui.QIntValidator(1, 100))
label_pixtab_header = QtWidgets.QLabel(
"Pixel Table\n", alignment=QtCore.Qt.AlignCenter
)
self.linetable = QtWidgets.QTableWidget()
self.linetable.verticalHeader().hide()
self.linetable.setColumnCount(2)
self.linetable.setHorizontalHeaderLabels(["Pixel", "Wavelength"])
self.linetable.setColumnWidth(0, 80)
self.linetable.setColumnWidth(1, 90)
self.linetable.setFixedWidth(180)
delegate = ValidatorDelegate(self.linetable)
self.linetable.setItemDelegate(delegate)
layout = QtWidgets.QHBoxLayout(self._main)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addWidget(self.line_editor)
pixtab_layout = QtWidgets.QVBoxLayout()
pixtab_layout.addWidget(label_pixtab_header)
pixtab_layout.addWidget(self.linetable)
layout.addLayout(pixtab_layout)
# Create Figure Canvas:
right_layout = QtWidgets.QVBoxLayout()
self.fig = Figure(figsize=(6, 6))
self.canvas = FigureCanvas(self.fig)
self.canvas.setSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
)
self.canvas.updateGeometry()
self.canvas.mpl_connect("key_press_event", self.on_key_press)
self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
self.canvas.setFocus()
right_layout.addWidget(self.canvas)
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
right_layout.addWidget(self.mpl_toolbar)
layout.addLayout(right_layout)
delegate.closeEditor.connect(self.canvas.setFocus)
# Plot some random data:
self.ax = self.fig.add_subplot(111)
self.ax.plot([0, 1, 5, 10, 20], [-1, 2, -4, 5, -2])
def on_key_press(self, e):
if e.key == "a":
self.add_point()
def add_point(self):
print("Select point...")
point = self.fig.ginput(1)
if not point:
return
x0, _ = point[0]
row = self.linetable.rowCount()
self.linetable.insertRow(row)
item = QtWidgets.QTableWidgetItem("%.2f" % x0)
item.setFlags(QtCore.Qt.ItemIsEnabled)
item.setBackground(QtGui.QColor("lightgray"))
self.linetable.setItem(row, 0, item)
index = self.linetable.model().index(row, 1)
self.linetable.edit(index)
if __name__ == "__main__":
# Launch App:
qapp = QtWidgets.QApplication(sys.argv)
app = GraphicInterface()
app.show()
qapp.exec_()
Related
I'm trying to create a compound widget similiar to the following:
A Rectangle overlayed with a button that is partially outside the rectangle's bounds.
Here is the code corresponding to that image:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QPoint
from PyQt5.QtGui import QResizeEvent
class MyWidget(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.layout = QHBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.layout)
self.lbl = QLabel()
self.lbl.setStyleSheet('background: #EE6622')
self.lbl.setFixedSize(125, 150)
self.layout.addWidget(self.lbl)
self.btn = QPushButton(parent=self)
self.btn.setStyleSheet('background: #ABCDEF')
self.btn.setFixedSize(25, 25)
def resizeEvent(self, event: QResizeEvent) -> None:
super().resizeEvent(event)
self.update_btn_pos()
def update_btn_pos(self):
pos = (
self.lbl.pos() +
QPoint(
self.lbl.rect().width() - int(self.btn.width() / 2),
-int(self.btn.height() / 2))
)
self.btn.move(pos)
if __name__ == "__main__":
a = QApplication(sys.argv)
window = MyWidget()
window.show()
a.exec()
My problem is that the widget's behaviour when resizing suggests that the button is not really "part of" that widget - it is cut-off as if it weren't there:
I tried to overwrite the sizeHint()-method to include the button, but that only solves the problem on startup, I can still resize the window manually to cut the button off again.
What must be changed in order to make this work?
I think I might have found a solution myself by adding the following to the __init__ - method:
self.layout.setContentsMargins(
0,
int(self.btn.height() / 2),
int(self.btn.width() / 2),
0
)
By setting the contentsMargin, the size of the big rectangle doesn't change because it is fixed and the parent widget still covers the space under the button:
I'm not sure if this is the *right way* to do it though ...
Alright, thanks to #musicamante this is the final code:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QResizeEvent
class MyWidget(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.lbl = QLabel()
self.lbl.setStyleSheet('background: #EE6622')
self.lbl.setFixedSize(125, 150)
self.layout.addWidget(self.lbl)
self.btn = QPushButton(parent=self)
self.btn.setStyleSheet('background: #ABCDEF')
self.btn.setFixedSize(25, 25)
# set contents margin of layout to half the button's size
self.layout.setContentsMargins(
*([int(self.btn.height() / 2), int(self.btn.width() / 2)]*2)
)
def resizeEvent(self, event: QResizeEvent) -> None:
super().resizeEvent(event)
self.update_btn_pos()
def update_btn_pos(self):
rect = self.btn.rect()
rect.moveCenter(self.lbl.geometry().topRight())
self.btn.move(rect.topLeft())
if __name__ == "__main__":
a = QApplication(sys.argv)
window = MyWidget()
window.show()
a.exec()
Result:
On paint event widget paints itself and all of his children clipped to his bounds. You can try to set button parent to MyWidget's parent, but you'll still have problem of button blocking part of some other widget or clipping on window's client area.
On the other hand there is no much difference between hovering button thats inside parent's widget and hovering button that sticks out, messing with other widgets.
I tried change QTableWidgetItem font, and complete that.
But, In Editmode, not change font.
(PS. I shouldn't give same style, so i don't use qss style sheet)
Below code, If Input F1 key, Size up current cell font size.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class MainWindow(QMainWindow):
def __init__(self, **kwargs):
super().__init__()
self.init_main()
self.init_table()
self.resize(500,500)
self.show()
def init_main(self):
self.main_widget = QWidget()
self.main_layout = QHBoxLayout()
self.main_widget.setLayout(self.main_layout)
self.setCentralWidget(self.main_widget)
def init_table(self):
self.table = QTableWidget(5, 5, self)
self.table.resize(500, 500)
# init QTableWidgetItem in QTableWidget (5 x 5),
[[self.table.setItem(row, col,QTableWidgetItem("text")) for row in range(5)] for col in range(5)]
def keyPressEvent(self, e):
# If input F1, resize font-size in current item.
if e.key() == Qt.Key_F1:
cur = self.table.currentItem()
font = cur.font()
font.setPointSize(30)
cur.setFont(font)
if __name__ == "__main__":
app = QCoreApplication.instance()
if app is None:
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
Setting the font on an item just changes the font for that item, not for its editor.
What you need to do is to create an item delegate (which is an object that is responsible of showing items and provide interaction with the underlying model, including the appropriate editor).
Since setting the font on a QTableWidgetItem equals to set the Qt.FontRole of the index, you can easily access that from the createEditor() function, call the base implementation to get the editor that is going to be returned, and apply the font to it if a font is set.
class FontDelegate(QStyledItemDelegate):
def createEditor(self, parent, opt, index):
editor = super().createEditor(parent, opt, index)
font = index.data(Qt.FontRole)
if font is not None:
editor.setFont(font)
return editor
class MainWindow(QMainWindow):
# ...
def init_table(self):
self.table = QTableWidget(5, 5)
self.main_layout.addWidget(self.table)
[[self.table.setItem(row, col, QTableWidgetItem("text")) for row in range(5)] for col in range(5)]
self.table.setItemDelegate(FontDelegate(self.table))
# ...
Unrelated note: the table should be added to the layout (as I did in the above code), and not just created as a child of the main window.
Start of the application
Plot the Graph
Full Screen
I have an application with 4 Box on the main window, and I want to had a full screen button in a windows which plot some graph, like on the Pictures on the top.
I first try a method to creating a fullScreen function in my code, linked to the button, but it is no work.
Here is my try :
class mainApplication(QWidget):
def __init__(self, parent=None):
super(mainApplication, self).__init__(parent)
self.layoutMap = {}
self.buttonMap = {}
# Figure Bottom Right
self.figure = plt.figure(figsize=(15,5))
self.figure.set_facecolor('0.915')
self.canvas = FigureCanvas(self.figure)
# Main Figure
self.setGeometry(600, 300, 1000, 600)
self.topLeft()
self.topRight()
self.bottomLeft()
self.bottomRight()
mainLayout = QGridLayout()
mainLayout.addWidget(self.topLeftBox, 1, 0)
mainLayout.addWidget(self.topRightBox, 1, 1)
mainLayout.addWidget(self.bottomLeftBox, 2, 0)
mainLayout.addWidget(self.bottomRightBox, 2, 1)
mainLayout.setRowStretch(1, 1)
mainLayout.setRowStretch(2, 1)
mainLayout.setColumnStretch(0, 1)
mainLayout.setColumnStretch(1, 1)
self.saveLayout(mainLayout, "main")
self.setLayout(mainLayout)
self.setWindowTitle("Title")
QApplication.setStyle("Fusion")
self.show()
def bottomRight(self):
self.bottomRightBox = QGroupBox("Bottom Right")
# Create Select Button
chooseButton = QPushButton("Select")
chooseButton.setMaximumWidth(100)
chooseButton.setMaximumHeight(20)
self.saveButton(chooseButton)
chooseButton.clicked.connect(self.selectFunction)
# Create Full Screen Button
fullScreenButton = QPushButton("Full")
fullScreenButton.setMaximumWidth(100)
fullScreenButton.setMaximumHeight(20)
self.saveButton(fullScreenButton)
fullScreenButton.clicked.connect(self.swichFullScreen)
# Create Layout
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.addWidget(chooseButton)
layout.addWidget(fullScreenButton)
layout.addStretch(1)
self.saveLayout(layout, "full")
# Add Layout to GroupBox
self.bottomRightBox.setLayout(layout)
def selectFunction(self):
# Select Data
filePath, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '/Data/')
df = pd.read_csv(str(filePath))
x = df.x.tolist()
y = df.y.tolist()
# Create Figure
self.figure.clf()
ax = self.figure.add_subplot(111)
ax.plot(x, y)
ax.set_facecolor('0.915')
ax.set_title('Graphique')
# Draw Graph
self.canvas.draw()
def saveLayout(self,obj, text):
self.layoutMap[text] = obj
def findLayout(self,text):
return self.layoutMap[text]
def saveButton(self,obj):
self.buttonMap[obj.text()] = obj
def findButton(self,text):
return self.buttonMap[text]
def swichFullScreen(self):
self.setLayout(self.findLayout("full"))
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = mainApplication()
sys.exit(app.exec_())
Have you an idea? because for example, if in my initialization I don't do :
self.setLayout(mainLayout)
but :
swichFullScreen()
I have the result that I want, so why call this fonction after the creation of my main layout don't work?
Moreover, I have try an other thing adapter from this : PyQt: Change GUI Layout after button is clicked
But it still not worked because when I clic on the button "full", it switch very well, but the normalWindow object has been delete so the button select stop to work.
If you have a solution for my first idea, I prefer because it avoid the creation of other class, but if it is not possible and that you find a solution for the second solution to avoid the destruction of the object, I take it too.
Here the code for my second solution :
class fullScreenApplication(QWidget):
def __init__(self, parent=None):
super(fullScreenApplication, self).__init__(parent)
self.setGeometry(600, 300, 1000, 600)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setGeometry(600, 300, 1000, 600)
self.normalWindows()
def normalWindows(self):
self.normalBox = mainApplication(self)
self.setCentralWidget(self.normalBox)
self.normalBox.findButton("Full").clicked.connect(self.fullScreenWindow)
self.show()
def fullScreenWindow(self):
self.FullBox = fullScreenApplication(self)
self.FullBox.setLayout(self.normalBox.findLayout("full"))
self.normalBox.findButton("Full").clicked.connect(self.normalWindows)
self.normalBox.findButton("Select").clicked.connect(self.normalBox.selectFunction)
self.setCentralWidget(self.FullBox)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
sys.exit(app.exec_())
Thank you
Try it:
import sys
import pandas as pd
import matplotlib.pyplot as plt
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class mainApplication(QWidget):
def __init__(self, parent=None):
super(mainApplication, self).__init__(parent)
self.layoutMap = {}
self.buttonMap = {}
# Figure Bottom Right
self.figure = plt.figure(figsize=(15,5))
self.figure.set_facecolor('0.915')
self.canvas = FigureCanvas(self.figure)
# Main Figure
# self.setGeometry(600, 300, 1000, 600)
self.topLeftBox = self.topLeft()
self.topRightBox = self.topRight()
self.bottomLeftBox = self.bottomLeft()
self.bottomRight()
self.mainLayout = QGridLayout()
self.mainLayout.addWidget(self.topLeftBox, 1, 0)
self.mainLayout.addWidget(self.topRightBox, 1, 1)
self.mainLayout.addWidget(self.bottomLeftBox, 2, 0)
self.mainLayout.addWidget(self.bottomRightBox, 2, 1)
self.mainLayout.setRowStretch(1, 1)
self.mainLayout.setRowStretch(2, 1)
self.mainLayout.setColumnStretch(0, 1)
self.mainLayout.setColumnStretch(1, 1)
self.saveLayout(self.mainLayout, "main")
self.setLayout(self.mainLayout)
self.setWindowTitle("Title")
QApplication.setStyle("Fusion")
# self.show()
def bottomRight(self):
self.bottomRightBox = QGroupBox("Bottom Right")
# Create Select Button
chooseButton = QPushButton("Select")
chooseButton.setMaximumWidth(100)
chooseButton.setMaximumHeight(20)
self.saveButton(chooseButton)
chooseButton.clicked.connect(self.selectFunction)
# Create Full Screen Button
self.fullScreenButton = QPushButton("Full")
self.fullScreenButton.setMaximumWidth(100)
self.fullScreenButton.setMaximumHeight(20)
self.saveButton(self.fullScreenButton)
self.fullScreenButton.clicked.connect(self.swichFullScreen)
# Create Layout
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.addWidget(chooseButton)
layout.addWidget(self.fullScreenButton)
layout.addStretch(1)
self.saveLayout(layout, "full")
# Add Layout to GroupBox
self.bottomRightBox.setLayout(layout)
def selectFunction(self):
# Select Data
filePath, _ = QFileDialog.getOpenFileName(self, 'Open file', '/Data/')
df = pd.read_csv(str(filePath))
x = df.x.tolist()
y = df.y.tolist()
# Create Figure
self.figure.clf()
ax = self.figure.add_subplot(111)
ax.plot(x, y)
ax.set_facecolor('0.915')
ax.set_title('Graphique')
# Draw Graph
self.canvas.draw()
def saveLayout(self,obj, text):
self.layoutMap[text] = obj
def findLayout(self,text):
return self.layoutMap[text]
def saveButton(self,obj):
self.buttonMap[obj.text()] = obj
def findButton(self,text):
return self.buttonMap[text]
def swichFullScreen(self):
# self.setLayout(self.findLayout("full")) # ---
# self.show() # ---
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
if self.sender().text()== "Full":
self.topLeftBox.hide()
self.topRightBox.hide()
self.bottomLeftBox.hide()
self.bottomRightBox.hide()
self.mainLayout.addWidget(self.bottomRightBox, 0, 0, 1, 2)
self.bottomRightBox.show()
self.fullScreenButton.setText("NoFull")
else:
self.bottomRightBox.hide()
self.topLeftBox.show()
self.topRightBox.show()
self.bottomLeftBox.show()
self.mainLayout.addWidget(self.bottomRightBox, 2, 1)
self.bottomRightBox.show()
self.fullScreenButton.setText("Full")
def topLeft(self):
textEdit = QTextEdit()
return textEdit
def topRight(self):
textEdit = QTextEdit()
return textEdit
def bottomLeft(self):
textEdit = QTextEdit()
return textEdit
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = mainApplication()
mainWindow.setGeometry(200, 100, 1000, 600)
mainWindow.show()
sys.exit(app.exec_())
So I have this code:
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget, QVBoxLayout, QHBoxLayout, QComboBox, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from lang import getLang
import sys, os, configparser
config = configparser.ConfigParser()
config.read("Settings.ini")
# Config get setting and change setting
#print(config.get("Main", "language"))
#config.set("Main", "language", "danish")
#with open("Settings.ini", "w") as cfg_file:
#config.write(cfg_file)
class App(QMainWindow):
def __init__(self):
super().__init__()
# Window Settings
self.x, self.y, self.w, self.h = 0, 0, 300, 200
self.setGeometry(self.x, self.y, self.w, self.h)
self.window = MainWindow(self)
self.setCentralWidget(self.window)
self.setWindowTitle("Window title") # Window Title
self.show()
class MainWindow(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
layout = QVBoxLayout(self)
# Run this after settings
self.lang = getLang(config.get("Main", "language"))
# Initialize tabs
tab_holder = QTabWidget() # Create tab holder
tab_1 = QWidget() # Tab one
tab_2 = QWidget() # Tab two
# Add tabs
tab_holder.addTab(tab_1, self.lang["tab_1_title"]) # Add "tab1" to the tabs holder "tabs"
tab_holder.addTab(tab_2, self.lang["tab_2_title"]) # Add "tab2" to the tabs holder "tabs"
# Create first tab
tab_1.layout = QVBoxLayout(self)
tab_2.layout = QVBoxLayout(self)
# Buttons
button_start = QPushButton(self.lang["btn_start"])
button_stop = QPushButton(self.lang["btn_stop"])
button_test = QPushButton(self.lang["btn_test"])
# Button Extra
button_start.setToolTip("This is a tooltip for the button!") # Message to show when mouse hover
button_start.clicked.connect(self.on_click)
button_stop.clicked.connect(self.on_click)
button_test.clicked.connect(self.on_click)
#button_start.setEnabled(False)
# comboBox
label_language = QLabel("Language")
combo_language = QComboBox(self)
combo_language.addItem(self.lang["language_danish"])
combo_language.addItem(self.lang["language_english"])
# Move widgets
combo_language.move(50, 150)
label_language.move(50, 50)
# Tab Binding
self.AddToTab(tab_1, button_start)
self.AddToTab(tab_1, button_stop)
self.AddToTab(tab_2, label_language)
self.AddToTab(tab_2, combo_language)
# Add tabs to widget
tab_1.setLayout(tab_1.layout)
tab_2.setLayout(tab_2.layout)
layout.addWidget(tab_holder)
self.setLayout(layout)
#pyqtSlot()
def on_click(self):
button = self.sender().text()
if button == self.lang["btn_start"]:
print("Dank")
elif button == self.lang["btn_stop"]:
print("Not dank")
def AddToTab(self, tab, obj):
tab.layout.addWidget(obj)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Currently it creates a window that contains 2 buttons on tab one. A "Start" and "Stop" button with no actual function yet other than printing text.
On tab 2 I have a label saying "Language:" and a dropdown menu that contains "Danish" and "English".
The problem I have with this, is that it's placement is really really weird and annoying as shown here:
I'm not sure how to change the placement as I can't just use .move on the text label, buttons and dropdown menu since they are placed in tabs.
For example, on tab two I would like the label "Language:" to be right to the left of the dropdown menu.
The problem is caused because you are using QVBoxLayout to set the widgets inside each tab. The task of the layout is to manage the position and size of the widgets so you can not use move(), besides it is not necessary.
The solution is that you create a custom layout for each tab, but keeping an order will create a custom widget for each tab, in the case of the first tab I'll continue using QVBoxlayout but add a stretch so that the widget stays stuck in the top position. In the second case I will combine a QVBoxLayout with a QHBoxLayout, the QHBoxLayout will use it to place the QLabel and the QComboBox and the QVBoxLayout will use it to push the widgets to the top position.
Implementing the above, I have omitted the lang for obvious reasons, we get the following:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys, os, configparser
config = configparser.ConfigParser()
config.read("Settings.ini")
# Config get setting and change setting
#print(config.get("Main", "language"))
#config.set("Main", "language", "danish")
#with open("Settings.ini", "w") as cfg_file:
#config.write(cfg_file)
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
# Window Settings
self.x, self.y, self.w, self.h = 0, 0, 300, 200
self.setGeometry(self.x, self.y, self.w, self.h)
self.window = MainWindow(self)
self.setCentralWidget(self.window)
self.setWindowTitle("Window title") # Window Title
self.show()
class GeneralWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(GeneralWidget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
# Buttons
button_start = QtWidgets.QPushButton("start") #self.lang["btn_start"])
button_stop = QtWidgets.QPushButton("stop") #self.lang["btn_stop"])
# Button Extra
button_start.setToolTip("This is a tooltip for the button!") # Message to show when mouse hover
button_start.clicked.connect(self.on_click)
button_stop.clicked.connect(self.on_click)
lay.addWidget(button_start)
lay.addWidget(button_stop)
lay.addStretch()
#QtCore.pyqtSlot()
def on_click(self):
button = self.sender().text()
if button == self.lang["btn_start"]:
print("Dank")
elif button == self.lang["btn_stop"]:
print("Not dank")
class OptionsWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(OptionsWidget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
hlay = QtWidgets.QHBoxLayout()
lay.addLayout(hlay)
lay.addStretch()
label_language = QtWidgets.QLabel("Language")
combo_language = QtWidgets.QComboBox(self)
combo_language.addItem("item1") #self.lang["language_danish"])
combo_language.addItem("item2") #self.lang["language_english"])
hlay.addWidget(label_language)
hlay.addWidget(combo_language)
class MainWindow(QtWidgets.QWidget):
def __init__(self, parent):
super(MainWindow, self).__init__(parent)
layout = QtWidgets.QVBoxLayout(self)
# Run this after settings
# self.lang = getLang(config.get("Main", "language"))
# Initialize tabs
tab_holder = QtWidgets.QTabWidget() # Create tab holder
tab_1 = GeneralWidget() # Tab one
tab_2 = OptionsWidget() # Tab two
# Add tabs
tab_holder.addTab(tab_1, "General") #self.lang["tab_1_title"]) # Add "tab1" to the tabs holder "tabs"
tab_holder.addTab(tab_2, "Options") #self.lang["tab_2_title"]) # Add "tab2" to the tabs holder "tabs"
layout.addWidget(tab_holder)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
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()