I am trying to create a custom widget RangeSpinBox. The widget doesn't auto fit in a QTableWidget like in the image attached below.
import sys
from PySide import QtGui
class RangeSpinBox(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super(RangeSpinBox, self).__init__(*args, **kwargs)
self.__minimum = 0
self.__maximum = 100
main_layout = QtGui.QHBoxLayout()
self.__minimum_spin_box = QtGui.QSpinBox()
self.__range_label = QtGui.QLabel('-')
self.__maximum_spin_box = QtGui.QSpinBox()
main_layout.addWidget(self.__minimum_spin_box)
main_layout.addWidget(self.__range_label)
main_layout.addWidget(self.__maximum_spin_box)
self.setLayout(main_layout)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
spin_box = RangeSpinBox()
table_widget = QtGui.QTableWidget()
table_widget.setColumnCount(2)
table_widget.setRowCount(1)
table_widget.setCellWidget(0, 0, spin_box)
table_widget.setCellWidget(0, 1, QtGui.QSpinBox())
table_widget.show()
app.exec_()
You need to remove the default margins on the layout, and also change the size-policy on the spin-boxes to expand in both directions:
main_layout = QtGui.QHBoxLayout()
main_layout.setContentsMargins(0, 0, 0, 0)
size_policy = QtGui.QSizePolicy(
QtGui.QSizePolicy.MinimumExpanding,
QtGui.QSizePolicy.MinimumExpanding)
self.__minimum_spin_box = QtGui.QSpinBox()
self.__minimum_spin_box.setSizePolicy(size_policy)
self.__range_label = QtGui.QLabel('-')
self.__maximum_spin_box = QtGui.QSpinBox()
self.__maximum_spin_box.setSizePolicy(size_policy)
Related
I am trying to access dynamically created Labels and LineEdit to change their texts.
I have no idea how is that possible ?
As an example, when Start button is clicked it should change the text of PS1 QLineEdit from XXXX to YYYY .
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("BiPolar Power Supply Testing")
widget_map = {}
tab_widget = QtWidgets.QTabWidget()
self.setCentralWidget(tab_widget)
pstest_widget = QtWidgets.QWidget()
tab_widget.addTab(pstest_widget, "PS Tests")
pstest_vlay = QtWidgets.QVBoxLayout()
for i in range(1, 9):
title = "PS{}".format(i)
group_box = MainWindow.create_pstest_element(title)
pstest_vlay.addWidget(group_box)
self.PSFStart_btn = QtWidgets.QPushButton("Start")
self.PSFStop_btn = QtWidgets.QPushButton("Stop")
pstest_vlay.addWidget(self.PSFStart_btn)
pstest_vlay.addWidget(self.PSFStop_btn)
pstest_vlay.addStretch()
grid_lay_1 = QtWidgets.QGridLayout(pstest_widget)
#grid_lay_1.addWidget(pstest_widget)
grid_lay_1.addLayout(pstest_vlay, 0, 0)
#staticmethod
def create_pstest_element(title):
group_box = QtWidgets.QGroupBox(title)
grid = QtWidgets.QGridLayout()
serial_label = QtWidgets.QLabel("Serial No:")
serial_lineedit = QtWidgets.QLineEdit("XXXX")
grid.addWidget(serial_label, 0, 0)
grid.addWidget(serial_lineedit, 0, 1)
group_box.setLayout(grid)
return group_box
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Here is how the GUI looks like:
The current design makes it difficult to access the widgets since you do not save access to the elements (you could use a filter using findChildren but that method is not scalable or elegant.).
In these cases it is better than creating a class that inherits from QGroupBox by making internal elements such as the QLabel and QLineEdit class members. On the other hand, having many QGroupBox, it is best to use a container that allows us to access each element by means of an index or key, in this one a list is enough.
class GroupBox(QtWidgets.QGroupBox):
def __init__(self, title, parent=None):
super().__init__(title, parent)
grid = QtWidgets.QGridLayout()
self.serial_label = QtWidgets.QLabel("Serial No:")
self.serial_lineedit = QtWidgets.QLineEdit("XXXX")
grid.addWidget(self.serial_label, 0, 0)
grid.addWidget(self.serial_lineedit, 0, 1)
self.setLayout(grid)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("BiPolar Power Supply Testing")
tab_widget = QtWidgets.QTabWidget()
self.setCentralWidget(tab_widget)
pstest_widget = QtWidgets.QWidget()
tab_widget.addTab(pstest_widget, "PS Tests")
pstest_vlay = QtWidgets.QVBoxLayout()
self.group_boxes = []
for i in range(1, 9):
title = "PS{}".format(i)
group_box = GroupBox(title)
pstest_vlay.addWidget(group_box)
self.group_boxes.append(group_box)
self.PSFStart_btn = QtWidgets.QPushButton("Start")
self.PSFStop_btn = QtWidgets.QPushButton("Stop")
pstest_vlay.addWidget(self.PSFStart_btn)
pstest_vlay.addWidget(self.PSFStop_btn)
pstest_vlay.addStretch()
grid_lay_1 = QtWidgets.QGridLayout(pstest_widget)
# grid_lay_1.addWidget(pstest_widget)
grid_lay_1.addLayout(pstest_vlay, 0, 0)
self.PSFStart_btn.clicked.connect(self.on_start_clicked)
#QtCore.pyqtSlot()
def on_start_clicked(self):
group_box = self.group_boxes[0]
group_box.serial_lineedit.setText("YYYY")
After looking at some code I found on stackoverflow, I was able to find a way to add a table to a QmessageBox. Now that I have done that, I would like to place a drop down menu in the top right of the QmessageBox and I cannot figure out a way to do that (if it even is possible).
Here is my edited code:
from PyQt4.QtGui import *
from PyQt4.Qt import *
import sys
class MyMessageBox(QMessageBox):
def __init__(self):
QMessageBox.__init__(self)
self.setSizeGripEnabled (True)
self.setWindowTitle('Get Parent Script')
self.setIcon(self.Question)
#self.setText("Hello MessageBox")
self.addButton("Select", QMessageBox.ActionRole)
self.setStandardButtons(QMessageBox.Cancel)
#self.addWidget(QInputDialog())
self.addTableWidget (self)
currentClick = self.exec_()
def addTableWidget (self, parentItem) :
self.l = QVBoxLayout()
self.tableWidget = QTableWidget(parentItem)
self.tableWidget.setObjectName ('tableWidget')
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount(2)
self.tableWidget.setHorizontalHeaderLabels(QString("Nuke Script;File Modification Time;User").split(";"))
header = self.tableWidget.horizontalHeader()
header.setResizeMode(0, QHeaderView.ResizeToContents)
header.setResizeMode(1, QHeaderView.Stretch)
header.setResizeMode(2, QHeaderView.Stretch)
stringlist = {u'/SEQ/ZZ/ZZ_012_001/Comp/nuke/scripts/comp':u'user1', u'/SEQ/ZZ/ZZ_012_001/Comp/nuke/scripts/comp/hello': u'user2'}
row = 0
for key, value in stringlist.iteritems():
print key, value
nameitem = QTableWidgetItem(str(key))
codeitem = QTableWidgetItem(str(value))
self.tableWidget.setItem(row,0,nameitem)
self.tableWidget.setItem(row,1,codeitem)
row +=1
self.tableWidget.resize(1000, 170)
self.l.addWidget(self.tableWidget)
self.setLayout(self.l)
def event(self, e):
result = QMessageBox.event(self, e)
self.setMinimumWidth(0)
self.setMaximumWidth(16777215)
self.setMinimumHeight(0)
self.setMaximumHeight(16777215)
self.setSizePolicy(
QSizePolicy.Expanding,
QSizePolicy.Expanding
)
self.resize(1000, 300)
return result
def run_cli():
#app = QtWidgets.QApplication(sys.argv)
app = QApplication(sys.argv)
MyMessageBox()
if __name__ == '__main__':
run_cli()
In your case it is not optimal to use QMessageBox since I involve unnecessary work because this widget already has a predefined layout, instead you can create a widget based on a QDialog:
from PyQt4 import QtCore, QtGui
class Dialog(QtGui.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
label = QtGui.QLabel("Text")
combo = QtGui.QComboBox()
combo.addItems(["option1", "option2", "option3"])
self.tableWidget = QtGui.QTableWidget(2, 3)
self.tableWidget.setHorizontalHeaderLabels(
QtCore.QString("Nuke Script;File Modification Time;User").split(";")
)
header = self.tableWidget.horizontalHeader()
header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents)
header.setResizeMode(1, QtGui.QHeaderView.Stretch)
header.setResizeMode(2, QtGui.QHeaderView.Stretch)
stringlist = {
u"/SEQ/ZZ/ZZ_012_001/Comp/nuke/scripts/comp": u"user1",
u"/SEQ/ZZ/ZZ_012_001/Comp/nuke/scripts/comp/hello": u"user2",
}
for row, (key, value) in enumerate(stringlist.iteritems()):
nameitem = QtGui.QTableWidgetItem(str(key))
codeitem = QtGui.QTableWidgetItem(str(value))
self.tableWidget.setItem(row, 0, nameitem)
self.tableWidget.setItem(row, 1, codeitem)
box = QtGui.QDialogButtonBox(
QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel,
centerButtons=True,
)
box.accepted.connect(self.accept)
box.rejected.connect(self.reject)
lay = QtGui.QGridLayout(self)
lay.addWidget(label, 0, 0)
lay.addWidget(combo, 0, 1)
lay.addWidget(self.tableWidget, 1, 0, 1, 2)
lay.addWidget(box, 2, 0, 1, 2)
self.resize(640, 240)
def run_cli():
import sys
app = QtGui.QApplication(sys.argv)
w = Dialog()
w.exec_()
if __name__ == "__main__":
run_cli()
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_())
Consider this example:
#!/usr/bin/env python
import sys,os
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import Qt
class MainWindow(QtWidgets.QMainWindow):
class ScrollAreaWheel(QtWidgets.QScrollArea): # SO:9475772
def __init__(self, parent=None):
super(MainWindow.ScrollAreaWheel, self).__init__(parent)
self.parent = parent
def wheelEvent(self, event):
print("wheelEvent", event.angleDelta().y())
def __init__(self):
#~ self.do_init = QtCore.QEvent.registerEventType()
QtWidgets.QMainWindow.__init__(self)
self.setMinimumWidth(1000)
self.setMinimumHeight(400)
self.frame1 = QtWidgets.QFrame(self)
self.frame1.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame1layout = QtWidgets.QGridLayout(self.frame1)
self.frame1layout.setSpacing(0);
self.frame1layout.setContentsMargins(0,0,0,0);
self.frame1widget = QtWidgets.QWidget()
self.frame1widget.setLayout(QtWidgets.QGridLayout())
self.frame1layout.addWidget(self.frame1widget)
self.frame1scroll = MainWindow.ScrollAreaWheel(self) #QtWidgets.QScrollArea()
self.frame1scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.frame1scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.frame1widget.layout().addWidget(self.frame1scroll, 0, 0) #, Qt.AlignCenter)
#self.frame1scrolllayout = QtWidgets.QHBoxLayout(self.frame1scroll)
self.frame1scrolllayout = QtWidgets.QGridLayout(self.frame1scroll)
self.frame1scroll.setWidget(self.frame1scrolllayout.widget())
self.frame1scroll.setWidgetResizable(True)
self.frame1scroll.setAlignment(Qt.AlignCenter)
self.frame1label = QtWidgets.QLabel()
self.frame1scrolllayout.addWidget(self.frame1label, 0, 0, Qt.AlignCenter) ##
pixmap = QtGui.QPixmap(200, 100)
pixmap.fill(Qt.red)
self.frame1label.setPixmap(pixmap)
self.frame2 = QtWidgets.QFrame(self)
self.frame2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame2layout = QtWidgets.QHBoxLayout(self.frame2)
self.frame2layout.setSpacing(0);
self.frame2layout.setContentsMargins(0,0,0,0);
self.frame2scroll = QtWidgets.QScrollArea(self)
self.frame2scroll.setWidgetResizable(True)
self.frame2widget = QtWidgets.QWidget()
self.frame2widget.setLayout(QtWidgets.QGridLayout())
self.frame2scroll.setWidget(self.frame2widget)
self.frame2layout.addWidget(self.frame2scroll)
self.mainwid = QtWidgets.QWidget()
self.mainwid.setLayout(QtWidgets.QGridLayout())
self.setCentralWidget(self.mainwid)
self.splitter1 = QtWidgets.QSplitter(Qt.Horizontal)
self.splitter1.addWidget(self.frame1)
self.splitter1.addWidget(self.frame2)
self.splitter1.setSizes([600, 600]); # equal splitter at start
self.mainwid.layout().addWidget(self.splitter1)
self.mainwid.layout().update()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
main = MainWindow()
main.show()
sys.exit(app.exec_())
It generates this (Ubuntu 18.04):
I want to use mousewheel only on the left QScrollArea, for which I've made a separate class. However, its wheelEvent fires only when I'm outside the red box, not when I hover over it. How can I make ScrollAreaWheel.wheelEvent fire even when mouse is over the child label (the red box)?
You are the QLabel placing on top of the QScrollArea instead of placing it inside, visually it is the same but at the level of events it is not.
from PyQt5 import QtCore, QtGui, QtWidgets
class ScrollAreaWheel(QtWidgets.QScrollArea):
def wheelEvent(self, event):
print("wheelEvent", event.angleDelta().y())
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setMinimumSize(1000, 400)
frame1 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.StyledPanel)
scrollarea1 = ScrollAreaWheel(widgetResizable=True)
scrollarea1.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
scrollarea1.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
widget1 = QtWidgets.QWidget()
scrollarea1.setWidget(widget1)
label_lay = QtWidgets.QGridLayout(widget1)
lay1 = QtWidgets.QVBoxLayout(frame1)
lay1.addWidget(scrollarea1)
pixmap = QtGui.QPixmap(200, 100)
pixmap.fill(QtCore.Qt.red)
label = QtWidgets.QLabel(pixmap=pixmap)
label_lay.addWidget(label, 0, 0, QtCore.Qt.AlignCenter)
#==============================
frame2 = QtWidgets.QFrame(frameShape=QtWidgets.QFrame.StyledPanel)
scrollarea2 = QtWidgets.QScrollArea(widgetResizable=True)
scrollarea2.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
scrollarea2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
widget2 = QtWidgets.QWidget()
scrollarea2.setWidget(widget2)
splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
splitter.addWidget(frame1)
splitter.addWidget(frame2)
splitter.setSizes([600, 600])
self.setCentralWidget(splitter)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
I am new to pyqt. I am doing a program that allows you clicks on the picture and remember the coordinates of points you clicks and draw a stickfigure on a widget of the GUI. My code right now can prompt out a new window to show a polygon with 4 points. However, I hope it can be displayed on the ui file I alreay made by pyqt. The object name for the widget is called widget.I hope someone can help me to modify the code to display the polygon on the gui widget not prompting out a new window.
Thank you so much!!!
import sys
from PyQt4.QtCore import *
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from Main_window import *
global imgloc
imgloc = "1.jpg"
array = []
clicks = 0
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.local_image = QImage(imgloc)
self.imageLocation = imgloc
self.local_scene = QGraphicsScene()
self.pixMapItem = QGraphicsPixmapItem(QPixmap(self.local_image), None, self.local_scene)
self.ui.graphicsView_5.setScene( self.local_scene )
self.pixMapItem.mousePressEvent = self.pixelSelect
def pixelSelect(self,event):
global imgloc
a = event.pos().x()
b = event.pos().y()
global clicks
global array
if clicks != 4:
clicks += 1
point = QPoint(a,b)
array.append(point)
else:
clicks = 0
dialog = DialogBody()
dialog.show()
dialog.exec_()
array = []
class DialogBody(QDialog):
def __init__(self,parent=None):
super(QDialog,self).__init__(parent)
self.setGeometry(100, 100, QImage(imgloc).height(), QImage(imgloc).width())
def paintEvent(self,e):
qp = QtGui.QPainter()
qp.begin(self)
self.drawBody(qp)
qp.end()
def drawBody(self, qp):
qp.setPen(QtCore.Qt.red)
qp.drawPolygon(array[0],array[1],array[2],array[3])
qp.drawEllipse(array[0],2,2)
qp.drawEllipse(array[1],2,2)
qp.drawEllipse(array[2],2,2)
qp.drawEllipse(array[3],2,2)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp= MyForm()
myapp.show()
sys.exit(app.exec_())
Looks like you want to draw items on QGraphicsScene? In this case you could add items to the scene:
#!/usr/bin/env python
import sys
from PyQt4 import QtCore, QtGui
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.scene = QtGui.QGraphicsScene()
self.view = QtGui.QGraphicsView(self.scene)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.view)
self.setLayout(layout)
self.pixmap_item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap('image.png'), None, self.scene)
self.pixmap_item.mousePressEvent = self.pixelSelect
self.click_positions = []
def pixelSelect(self, event):
self.click_positions.append(event.pos())
if len(self.click_positions) < 4:
return
pen = QtGui.QPen(QtCore.Qt.red)
self.scene.addPolygon(QtGui.QPolygonF(self.click_positions), pen)
for point in self.click_positions:
self.scene.addEllipse(point.x(), point.y(), 2, 2, pen)
self.click_positions = []
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
widget = MainWidget()
widget.resize(640, 480)
widget.show()
sys.exit(app.exec_())
QGraphicsScene has many features.
Read Graphics View Framework overview in Qt docs.