I'm drawing a line between two widgets (two push buttons) into a graphics view with their positions as reference. But the line is drawn in a wrong place.
I tried using functions like mapToGlobal or mapToParent with different results, but it's still wrong. In the same class I have another method that draws lines with the mouse, and it works ok. I was taking it like a reference, but it seems that the events position has a different coordinate system. I don't know why this is happening.
The buttons and the graphics view are inside a Widget, which is also inside a window.
Here it is the class:
from PyQt4 import QtGui, QtCore
class WiringGraphicsView(QtGui.QGraphicsView):
def __init__(self, parent):
QtGui.QGraphicsView.__init__(self, parent)
self.setScene(QtGui.QGraphicsScene(self))
#self.setSceneRect(QtCore.QRectF(self.viewport().rect()))
def mousePressEvent(self, event):
self._start = event.pos()
def mouseReleaseEvent(self, event):
start = QtCore.QPointF(self.mapToScene(self._start))
end = QtCore.QPointF(self.mapToScene(event.pos()))
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0) )
pen = QtGui.QPen(brush, 2)
line = QtGui.QGraphicsLineItem(QtCore.QLineF(start, end))
line.setPen(pen)
self.scene().addItem( line )
def paintWire(self, start_widget, end_widget):
start_position = QtCore.QPointF(self.mapToScene(start_widget.pos()))
end_position = QtCore.QPointF(self.mapToScene(end_widget.pos()))
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0) )
pen = QtGui.QPen(brush, 2)
line = QtGui.QGraphicsLineItem(QtCore.QLineF(start_position, end_position))
line.setPen(pen)
self.scene().addItem( line )
UPDATE: At this point I've tried several things: Since the buttons were contained in a QWidget object, I take them out from there. I put them in a GroupBox instead. Also tried without containers. I don't get satisfactory results. Honestly I don't know how to do this properly considering that I'm using Qt designer and creating class files for "promoted" widgets (in this case is the GraphicsView) and set up some properties using the UpdateUi method in the main file
UPDATE 2: Here it is the file where the application is loaded:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import ui_wolfsonmixerwindow
class WolfsonMixerWindow(QMainWindow, ui_wolfsonmixerwindow.Ui_WolfsonMixerWindow):
def __init__(self, parent=None):
super(WolfsonMixerWindow, self).__init__(parent)
self.setupUi(self)
self.updateUi()
def updateUi(self):
#self.btn_AIF1RX1.setText("Hola")
menu_plugin = QMenu()
menu_unplug = QMenu()
menu_plugin.addAction('Action 1', self.plugin )
self.btn_AIF1RX1_2.setMenu(menu_plugin)
self.btn_AIF1TX1_5.setAllowDrag(False)
self.btn_AIF1TX1_5.setMenu(menu_unplug)
start = self.btn_AIF1RX1_2
end = self.btn_AIF1TX1_5
#self.graphicsView.scene().addWidget(self.btn_AIF1RX1_2)
#self.graphicsView.scene().addWidget(self.btn_AIF1TX1_5)
#self.graphicsView.setWidgets(start, end)
#HERE I CALL THE PAINTWIRE METHOD
self.graphicsView.paintWire(start, end)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
form = WolfsonMixerWindow()
form.show()
app.exec_()
And the uic file:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_wolfsonmixerwindow.ui'
#
# Created: Thu Feb 19 21:51:35 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_WolfsonMixerWindow(object):
def setupUi(self, WolfsonMixerWindow):
WolfsonMixerWindow.setObjectName(_fromUtf8("WolfsonMixerWindow"))
WolfsonMixerWindow.resize(562, 480)
self.centralwidget = QtGui.QWidget(WolfsonMixerWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayoutWidget = QtGui.QWidget(self.centralwidget)
self.gridLayoutWidget.setGeometry(QtCore.QRect(200, 10, 241, 101))
self.gridLayoutWidget.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.gridLayoutWidget.setObjectName(_fromUtf8("gridLayoutWidget"))
self.gridLayout = QtGui.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)
self.gridLayout.setMargin(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.QHBox_Playback = QtGui.QHBoxLayout()
self.QHBox_Playback.setObjectName(_fromUtf8("QHBox_Playback"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label_2 = QtGui.QLabel(self.gridLayoutWidget)
self.label_2.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout.addWidget(self.label_2)
self.label = QtGui.QLabel(self.gridLayoutWidget)
self.label.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName(_fromUtf8("label"))
self.verticalLayout.addWidget(self.label)
self.btn_AIF1RX1 = DragButton(self.gridLayoutWidget)
self.btn_AIF1RX1.setBaseSize(QtCore.QSize(0, 0))
self.btn_AIF1RX1.setMouseTracking(True)
self.btn_AIF1RX1.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1RX1.setText(_fromUtf8(""))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/audio-input-line.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btn_AIF1RX1.setIcon(icon)
self.btn_AIF1RX1.setAutoDefault(False)
self.btn_AIF1RX1.setDefault(False)
self.btn_AIF1RX1.setFlat(True)
self.btn_AIF1RX1.setObjectName(_fromUtf8("btn_AIF1RX1"))
self.verticalLayout.addWidget(self.btn_AIF1RX1)
self.QHBox_Playback.addLayout(self.verticalLayout)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.label_3 = QtGui.QLabel(self.gridLayoutWidget)
self.label_3.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label_3.setAlignment(QtCore.Qt.AlignCenter)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.verticalLayout_2.addWidget(self.label_3)
self.label_4 = QtGui.QLabel(self.gridLayoutWidget)
self.label_4.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label_4.setAlignment(QtCore.Qt.AlignCenter)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.verticalLayout_2.addWidget(self.label_4)
self.btn_AIF1RX2 = QtGui.QPushButton(self.gridLayoutWidget)
self.btn_AIF1RX2.setBaseSize(QtCore.QSize(0, 0))
self.btn_AIF1RX2.setMouseTracking(True)
self.btn_AIF1RX2.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1RX2.setText(_fromUtf8(""))
self.btn_AIF1RX2.setIcon(icon)
self.btn_AIF1RX2.setAutoDefault(False)
self.btn_AIF1RX2.setDefault(False)
self.btn_AIF1RX2.setFlat(True)
self.btn_AIF1RX2.setObjectName(_fromUtf8("btn_AIF1RX2"))
self.verticalLayout_2.addWidget(self.btn_AIF1RX2)
self.QHBox_Playback.addLayout(self.verticalLayout_2)
self.gridLayout.addLayout(self.QHBox_Playback, 1, 0, 1, 1)
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
self.horizontalLayout_3.setContentsMargins(-1, -1, 0, -1)
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.verticalLayout_3 = QtGui.QVBoxLayout()
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
self.label_6 = QtGui.QLabel(self.gridLayoutWidget)
self.label_6.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label_6.setAlignment(QtCore.Qt.AlignCenter)
self.label_6.setObjectName(_fromUtf8("label_6"))
self.verticalLayout_3.addWidget(self.label_6)
self.label_5 = QtGui.QLabel(self.gridLayoutWidget)
self.label_5.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label_5.setAlignment(QtCore.Qt.AlignCenter)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.verticalLayout_3.addWidget(self.label_5)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.btn_AIF1TX1_1 = QtGui.QPushButton(self.gridLayoutWidget)
self.btn_AIF1TX1_1.setMouseTracking(False)
self.btn_AIF1TX1_1.setFocusPolicy(QtCore.Qt.StrongFocus)
self.btn_AIF1TX1_1.setAcceptDrops(True)
self.btn_AIF1TX1_1.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX1_1.setText(_fromUtf8(""))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/input_small.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btn_AIF1TX1_1.setIcon(icon1)
self.btn_AIF1TX1_1.setFlat(True)
self.btn_AIF1TX1_1.setObjectName(_fromUtf8("btn_AIF1TX1_1"))
self.horizontalLayout.addWidget(self.btn_AIF1TX1_1)
self.btn_AIF1TX1_2 = QtGui.QPushButton(self.gridLayoutWidget)
self.btn_AIF1TX1_2.setAcceptDrops(True)
self.btn_AIF1TX1_2.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX1_2.setText(_fromUtf8(""))
self.btn_AIF1TX1_2.setIcon(icon1)
self.btn_AIF1TX1_2.setFlat(True)
self.btn_AIF1TX1_2.setObjectName(_fromUtf8("btn_AIF1TX1_2"))
self.horizontalLayout.addWidget(self.btn_AIF1TX1_2)
self.btn_AIF1TX1_3 = QtGui.QPushButton(self.gridLayoutWidget)
self.btn_AIF1TX1_3.setAcceptDrops(True)
self.btn_AIF1TX1_3.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX1_3.setText(_fromUtf8(""))
self.btn_AIF1TX1_3.setIcon(icon1)
self.btn_AIF1TX1_3.setFlat(True)
self.btn_AIF1TX1_3.setObjectName(_fromUtf8("btn_AIF1TX1_3"))
self.horizontalLayout.addWidget(self.btn_AIF1TX1_3)
self.btn_AIF1TX1_4 = QtGui.QPushButton(self.gridLayoutWidget)
self.btn_AIF1TX1_4.setAcceptDrops(True)
self.btn_AIF1TX1_4.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX1_4.setText(_fromUtf8(""))
self.btn_AIF1TX1_4.setIcon(icon1)
self.btn_AIF1TX1_4.setFlat(True)
self.btn_AIF1TX1_4.setObjectName(_fromUtf8("btn_AIF1TX1_4"))
self.horizontalLayout.addWidget(self.btn_AIF1TX1_4)
self.verticalLayout_3.addLayout(self.horizontalLayout)
self.horizontalLayout_3.addLayout(self.verticalLayout_3)
self.verticalLayout_4 = QtGui.QVBoxLayout()
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
self.label_7 = QtGui.QLabel(self.gridLayoutWidget)
self.label_7.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label_7.setAlignment(QtCore.Qt.AlignCenter)
self.label_7.setObjectName(_fromUtf8("label_7"))
self.verticalLayout_4.addWidget(self.label_7)
self.label_8 = QtGui.QLabel(self.gridLayoutWidget)
self.label_8.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label_8.setAlignment(QtCore.Qt.AlignCenter)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.verticalLayout_4.addWidget(self.label_8)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setSpacing(1)
self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.btn_AIF1TX2_1 = QtGui.QPushButton(self.gridLayoutWidget)
self.btn_AIF1TX2_1.setAcceptDrops(True)
self.btn_AIF1TX2_1.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX2_1.setText(_fromUtf8(""))
self.btn_AIF1TX2_1.setIcon(icon1)
self.btn_AIF1TX2_1.setFlat(True)
self.btn_AIF1TX2_1.setObjectName(_fromUtf8("btn_AIF1TX2_1"))
self.horizontalLayout_2.addWidget(self.btn_AIF1TX2_1)
self.btn_AIF1TX2_2 = QtGui.QPushButton(self.gridLayoutWidget)
self.btn_AIF1TX2_2.setAcceptDrops(True)
self.btn_AIF1TX2_2.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX2_2.setText(_fromUtf8(""))
self.btn_AIF1TX2_2.setIcon(icon1)
self.btn_AIF1TX2_2.setFlat(True)
self.btn_AIF1TX2_2.setObjectName(_fromUtf8("btn_AIF1TX2_2"))
self.horizontalLayout_2.addWidget(self.btn_AIF1TX2_2)
self.btn_AIF1TX2_3 = QtGui.QPushButton(self.gridLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.btn_AIF1TX2_3.sizePolicy().hasHeightForWidth())
self.btn_AIF1TX2_3.setSizePolicy(sizePolicy)
self.btn_AIF1TX2_3.setAcceptDrops(True)
self.btn_AIF1TX2_3.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX2_3.setText(_fromUtf8(""))
self.btn_AIF1TX2_3.setIcon(icon1)
self.btn_AIF1TX2_3.setFlat(True)
self.btn_AIF1TX2_3.setObjectName(_fromUtf8("btn_AIF1TX2_3"))
self.horizontalLayout_2.addWidget(self.btn_AIF1TX2_3)
self.btn_AIF1TX2_4 = QtGui.QPushButton(self.gridLayoutWidget)
self.btn_AIF1TX2_4.setAcceptDrops(True)
self.btn_AIF1TX2_4.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX2_4.setText(_fromUtf8(""))
self.btn_AIF1TX2_4.setIcon(icon1)
self.btn_AIF1TX2_4.setFlat(True)
self.btn_AIF1TX2_4.setObjectName(_fromUtf8("btn_AIF1TX2_4"))
self.horizontalLayout_2.addWidget(self.btn_AIF1TX2_4)
self.verticalLayout_4.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3.addLayout(self.verticalLayout_4)
self.gridLayout.addLayout(self.horizontalLayout_3, 1, 1, 1, 1)
self.lbl_playback = QtGui.QLabel(self.gridLayoutWidget)
self.lbl_playback.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.lbl_playback.setTextFormat(QtCore.Qt.AutoText)
self.lbl_playback.setObjectName(_fromUtf8("lbl_playback"))
self.gridLayout.addWidget(self.lbl_playback, 0, 0, 1, 1)
self.label_9 = QtGui.QLabel(self.gridLayoutWidget)
self.label_9.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.label_9.setAlignment(QtCore.Qt.AlignCenter)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.gridLayout.addWidget(self.label_9, 0, 1, 1, 1)
self.dial = QtGui.QDial(self.centralwidget)
self.dial.setGeometry(QtCore.QRect(30, 360, 50, 64))
self.dial.setObjectName(_fromUtf8("dial"))
self.label_10 = QtGui.QLabel(self.centralwidget)
self.label_10.setGeometry(QtCore.QRect(20, 320, 52, 15))
self.label_10.setObjectName(_fromUtf8("label_10"))
self.widget = QtGui.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(160, 400, 331, 21))
self.widget.setObjectName(_fromUtf8("widget"))
self.groupBox = QtGui.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(130, 130, 361, 271))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.graphicsView = WiringGraphicsView(self.groupBox)
self.graphicsView.setGeometry(QtCore.QRect(40, 30, 291, 241))
self.graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.NoBrush)
self.graphicsView.setBackgroundBrush(brush)
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.btn_AIF1RX1_2 = DragButton(self.groupBox)
self.btn_AIF1RX1_2.setGeometry(QtCore.QRect(50, 50, 51, 31))
self.btn_AIF1RX1_2.setBaseSize(QtCore.QSize(0, 0))
self.btn_AIF1RX1_2.setMouseTracking(True)
self.btn_AIF1RX1_2.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1RX1_2.setText(_fromUtf8(""))
self.btn_AIF1RX1_2.setIcon(icon)
self.btn_AIF1RX1_2.setAutoDefault(False)
self.btn_AIF1RX1_2.setDefault(False)
self.btn_AIF1RX1_2.setFlat(True)
self.btn_AIF1RX1_2.setObjectName(_fromUtf8("btn_AIF1RX1_2"))
self.btn_AIF1TX1_5 = DragButton(self.groupBox)
self.btn_AIF1TX1_5.setGeometry(QtCore.QRect(270, 150, 41, 31))
self.btn_AIF1TX1_5.setMouseTracking(False)
self.btn_AIF1TX1_5.setFocusPolicy(QtCore.Qt.StrongFocus)
self.btn_AIF1TX1_5.setAcceptDrops(True)
self.btn_AIF1TX1_5.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1TX1_5.setText(_fromUtf8(""))
self.btn_AIF1TX1_5.setIcon(icon1)
self.btn_AIF1TX1_5.setFlat(True)
self.btn_AIF1TX1_5.setObjectName(_fromUtf8("btn_AIF1TX1_5"))
self.btn_AIF1RX1_3 = DragButton(self.groupBox)
self.btn_AIF1RX1_3.setGeometry(QtCore.QRect(60, 110, 51, 27))
self.btn_AIF1RX1_3.setBaseSize(QtCore.QSize(0, 0))
self.btn_AIF1RX1_3.setMouseTracking(True)
self.btn_AIF1RX1_3.setAcceptDrops(False)
self.btn_AIF1RX1_3.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
self.btn_AIF1RX1_3.setText(_fromUtf8(""))
self.btn_AIF1RX1_3.setIcon(icon)
self.btn_AIF1RX1_3.setAutoDefault(False)
self.btn_AIF1RX1_3.setDefault(False)
self.btn_AIF1RX1_3.setFlat(True)
self.btn_AIF1RX1_3.setObjectName(_fromUtf8("btn_AIF1RX1_3"))
WolfsonMixerWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(WolfsonMixerWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 562, 23))
self.menubar.setObjectName(_fromUtf8("menubar"))
WolfsonMixerWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(WolfsonMixerWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
WolfsonMixerWindow.setStatusBar(self.statusbar)
self.retranslateUi(WolfsonMixerWindow)
QtCore.QObject.connect(self.dial, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.label_10.setNum)
QtCore.QMetaObject.connectSlotsByName(WolfsonMixerWindow)
def retranslateUi(self, WolfsonMixerWindow):
WolfsonMixerWindow.setWindowTitle(_translate("WolfsonMixerWindow", "Wolfson Mixer", None))
self.label_2.setText(_translate("WolfsonMixerWindow", "AIF1RX1", None))
self.label.setText(_translate("WolfsonMixerWindow", "L", None))
self.label_3.setText(_translate("WolfsonMixerWindow", "AIF1RX2", None))
self.label_4.setText(_translate("WolfsonMixerWindow", "R", None))
self.label_6.setText(_translate("WolfsonMixerWindow", "AIF1TX1", None))
self.label_5.setText(_translate("WolfsonMixerWindow", "L", None))
self.label_7.setText(_translate("WolfsonMixerWindow", "AIF1TX2", None))
self.label_8.setText(_translate("WolfsonMixerWindow", "R", None))
self.lbl_playback.setText(_translate("WolfsonMixerWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Playback (from RPi)</span></p></body></html>", None))
self.label_9.setText(_translate("WolfsonMixerWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Record (to RPi)</span></p></body></html>", None))
self.label_10.setText(_translate("WolfsonMixerWindow", "TextLabel", None))
self.groupBox.setTitle(_translate("WolfsonMixerWindow", "GroupBox", None))
from wiringgraphicsview import WiringGraphicsView
from dragbutton import DragButton
import icons_rc
Here is an example how to draw a line between two QWidgets in a QGraphicsScene. In principle it is straightforward. The rectangle of a widget can be accessed by QGraphicsProxyWidget.geometry() and is in scene coordinates. So one can draw a line based on that.
Example:
from PySide import QtGui, QtCore
app = QtGui.QApplication([])
scene = QtGui.QGraphicsScene()
# put a button into the scene and move it
button1 = QtGui.QPushButton('Button 1')
scene_button1 = scene.addWidget(button1)
r1 = scene_button1.geometry()
r1.moveTo(-100, -50)
scene_button1.setGeometry(r1)
# put another button into the scene
button2 = QtGui.QPushButton('Button 2')
scene_button2 = scene.addWidget(button2)
r2 = scene_button2.geometry()
# add a line between the centers of each rectangles
scene.addLine(r1.x() + r1.width() / 2, r1.y() + r1.height() / 2, r2.x() + r2.width() / 2, r2.y() + r2.height() / 2)
# view on the scene
view = QtGui.QGraphicsView(scene)
view.resize(300, 200)
view.show()
app.exec_()
And it looks like:
And now the whole with dragging because it is not that trivial. Not the QGraphicsProxyWidget but the original QWidget, seems to get the mouse move/pressed events. We simply emit a new signal (dragged) and connect it to a function that can move the button in the scene around (using the return of scene.addWidget, the QGraphicsProxyWidget which is also a QGraphicsItem). It also redraws the line between the two buttons so they stay connected.
from PySide import QtGui, QtCore
class DraggablePushButton(QtGui.QPushButton):
"""
Extension of QPushButton that emits a dragged signal (QPointF which is the delta in movement of the mouse) as
long as it is pressed.
"""
dragged = QtCore.Signal(QtCore.QPointF)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def mousePressEvent(self, event):
self.position = event.globalPos()
def mouseMoveEvent(self, event):
# will only by called if the mouse is also pressed
position_now = event.globalPos()
self.dragged.emit(position_now - self.position)
self.position = position_now
def move_scene_button1_and_redraw_line(drag):
# move the button1 by a certain delta position and change line connecting them with it
scene_button1.moveBy(drag.x(), drag.y())
r1 = scene_button1.geometry()
line_item.setLine(r1.x() + r1.width() / 2, r1.y() + r1.height() / 2, r2.x() + r2.width() / 2, r2.y() + r2.height() / 2)
app = QtGui.QApplication([])
# the graphicsscene
scene = QtGui.QGraphicsScene()
scene.setSceneRect(-150, -100, 300, 200)
# put a draggable button into the scene
button1 = DraggablePushButton('Button 1')
scene_button1 = scene.addWidget(button1)
scene_button1.setPos(-100, -50)
r1 = scene_button1.geometry()
# connect dragged events to move of scene button
button1.dragged.connect(move_scene_button1_and_redraw_line)
# put another still standing button into the scene
button2 = QtGui.QPushButton('Button 2')
scene_button2 = scene.addWidget(button2)
r2 = scene_button2.geometry()
# draw line between button1 and button2
line_item = scene.addLine(r1.x() + r1.width() / 2, r1.y() + r1.height() / 2, r2.x() + r2.width() / 2, r2.y() + r2.height() / 2)
# view on the scene
view = QtGui.QGraphicsView(scene)
view.resize(330, 220)
view.show()
app.exec_()
And it still looks like:
Related
I am trying to use draggable QLabels for cropping an image. The basic idea of my code is segmenting characters in an image.
So, the user will first upload an image contains three characters to the program.
Then, he will specify the type of the plate, is it short or long by checking on the suitable checkbox. Based on the checkbox, three boxes (QLabels) with specific size will be shown to the user so he can drag each box on a character in the uploaded image. Once the user is finished placing the boxes on the characters, he can click on the Segment button to apply the cropping operation. The final result will be three images of the cropped characters.
I have done from the program interface and some functionality, However, I'm facing a problem with darg and cropping functions. I have tried different ways with dragging boxes (QLabels) but it's not working with me. I really don't know what's wrong in my code :(. I'm using python 3 and PyQt5.
This is my code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
from PyQt5.QtGui import QDrag, QPixmap, QPainter, QCursor
from PyQt5.QtCore import QMimeData, Qt
boxes_items = []
#=========================================================================
class DraggableLabel(QLabel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
event.accept()
event.acceptProposedAction()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
event.accept()
self.setCursor(QtGui.QCursor(QtCore.Qt.CloseHandCursor))
self.drag_start_position = event.pos()
def mouseMoveEvent(self, event):
if not (event.buttons() & Qt.LeftButton):
return
if (event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance():
return
drag = QDrag(self)
'''
mimedata = QMimeData()
#mimedata.setText(self.text())
mimedata.setImageData(self.pixmap().toImage())
drag.setMimeData(mimedata)
pixmap = QPixmap(self.size())
painter = QPainter(pixmap)
painter.drawPixmap(self.rect(), self.grab())
painter.end()
drag.setPixmap(pixmap)
'''
drag.setHotSpot(event.pos())
drag.exec_(Qt.CopyAction | Qt.MoveAction)
'''
class DropLabel(QLabel):
def __init__(self, *args, **kwargs):
QLabel.__init__(self, *args, **kwargs)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasText():
event.acceptProposedAction()
def dropEvent(self, event):
pos = event.pos()
self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
# text = event.mimeData().text()
# self.setText(text)
event.acceptProposedAction()
'''
#==========================================================================
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.setEnabled(True)
Dialog.resize(1050, 800)
Dialog.setMinimumSize(QtCore.QSize(1050, 800))
Dialog.setMaximumSize(QtCore.QSize(1050, 800))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../.designer/backup/project pic/images LPR icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
Dialog.setStyleSheet("background-color: rgb(217, 217, 217);\n"
"background-color: rgb(243, 243, 243);")
# Dialog.setAcceptDrops(True)
self.BrowesImageButton = QtWidgets.QPushButton(Dialog)
self.BrowesImageButton.setGeometry(QtCore.QRect(820, 60, 200, 60))
self.BrowesImageButton.setMinimumSize(QtCore.QSize(200, 60))
self.BrowesImageButton.setMaximumSize(QtCore.QSize(200, 60))
font = QtGui.QFont()
font.setFamily("Microsoft YaHei UI")
font.setPointSize(11)
font.setBold(True)
font.setWeight(75)
self.BrowesImageButton.setFont(font)
self.BrowesImageButton.setStyleSheet("")
self.BrowesImageButton.setCheckable(True)
self.BrowesImageButton.setObjectName("BrowesImageButton")
self.groupBox = QtWidgets.QGroupBox(Dialog)
self.groupBox.setGeometry(QtCore.QRect(820, 170, 211, 131))
font = QtGui.QFont()
font.setFamily("Microsoft YaHei")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.groupBox.setFont(font)
self.groupBox.setLayoutDirection(QtCore.Qt.LeftToRight)
self.groupBox.setObjectName("groupBox")
self.checkBox_Short = QtWidgets.QCheckBox(self.groupBox)
self.checkBox_Short.setGeometry(QtCore.QRect(20, 40, 141, 23))
font = QtGui.QFont()
font.setFamily("Adobe Heiti Std R")
font.setPointSize(10)
self.checkBox_Short.setFont(font)
self.checkBox_Short.setLayoutDirection(QtCore.Qt.LeftToRight)
self.checkBox_Short.setObjectName("checkBox_Short")
self.checkBox_Short.setEnabled(False)
self.checkBox_Long = QtWidgets.QCheckBox(self.groupBox)
self.checkBox_Long.setGeometry(QtCore.QRect(20, 80, 141, 23))
font = QtGui.QFont()
font.setFamily("Adobe Heiti Std R")
font.setPointSize(10)
self.checkBox_Long.setFont(font)
self.checkBox_Long.setLayoutDirection(QtCore.Qt.LeftToRight)
self.checkBox_Long.setObjectName("checkBox_Long")
self.checkBox_Long.setEnabled(False)
self.SegmentImageButton = QtWidgets.QPushButton(Dialog)
self.SegmentImageButton.setGeometry(QtCore.QRect(830, 330, 200, 60))
self.SegmentImageButton.setMinimumSize(QtCore.QSize(200, 60))
self.SegmentImageButton.setMaximumSize(QtCore.QSize(200, 60))
font = QtGui.QFont()
font.setFamily("Microsoft YaHei UI")
font.setPointSize(11)
font.setBold(True)
font.setWeight(75)
self.SegmentImageButton.setFont(font)
self.SegmentImageButton.setStyleSheet("")
self.SegmentImageButton.setCheckable(True)
self.SegmentImageButton.setObjectName("SegmentImageButton")
self.SegmentImageButton.setEnabled(False)
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(980, 470, 45, 45))
self.label.setMinimumSize(QtCore.QSize(45, 45))
self.label.setMaximumSize(QtCore.QSize(45, 45))
self.label.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
self.label.setMouseTracking(True)
self.label.setAcceptDrops(True)
self.label.setStyleSheet("border-color: rgb(238, 0, 0); border-width : 2.0px; border-style:inset;")
self.label.setFrameShape(QtWidgets.QFrame.Box)
self.label.setLineWidth(2)
self.label.setText("")
self.label.setObjectName("label")
self.label.hide()
'''
self.graphicsView = QtWidgets.QGraphicsView(Dialog)
self.graphicsView.setGeometry(QtCore.QRect(40, 40, 750, 500))
self.graphicsView.setMinimumSize(QtCore.QSize(750, 500))
self.graphicsView.setMaximumSize(QtCore.QSize(750, 500))
self.graphicsView.setObjectName("graphicsView")
'''
self.UserImageLbl = QtWidgets.QLabel(Dialog)
self.UserImageLbl.setGeometry(QtCore.QRect(40, 40, 750, 500))
self.UserImageLbl.setMinimumSize(QtCore.QSize(750, 500))
self.UserImageLbl.setMaximumSize(QtCore.QSize(750, 500))
self.UserImageLbl.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.UserImageLbl.setFrameShadow(QtWidgets.QFrame.Plain)
self.UserImageLbl.setLineWidth(1)
self.UserImageLbl.setMidLineWidth(0)
self.UserImageLbl.setText("")
self.UserImageLbl.setScaledContents(False)
self.UserImageLbl.setAlignment(QtCore.Qt.AlignCenter)
self.UserImageLbl.setObjectName("UserImageLbl")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(900, 470, 45, 45))
self.label_2.setMinimumSize(QtCore.QSize(45, 45))
self.label_2.setMaximumSize(QtCore.QSize(45, 45))
self.label_2.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
self.label_2.setMouseTracking(True)
self.label_2.setAcceptDrops(True)
self.label_2.setStyleSheet("border-color: rgb(238, 0, 0); border-width : 2.0px; border-style:inset;")
self.label_2.setFrameShape(QtWidgets.QFrame.Box)
self.label_2.setLineWidth(2)
self.label_2.setText("")
self.label_2.setObjectName("label_2")
self.label_2.hide()
self.label_3 = QtWidgets.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(820, 470, 45, 45))
self.label_3.setMinimumSize(QtCore.QSize(45, 45))
self.label_3.setMaximumSize(QtCore.QSize(45, 45))
self.label_3.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
self.label_3.setMouseTracking(True)
self.label_3.setAcceptDrops(True)
self.label_3.setStyleSheet("border-color: rgb(238, 0, 0); border-width : 2.0px; border-style:inset;")
self.label_3.setFrameShape(QtWidgets.QFrame.Box)
self.label_3.setLineWidth(2)
self.label_3.setText("")
self.label_3.setObjectName("label_3")
self.label_3.hide()
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
#Add labels in boxes items list
boxes_items.append(self.label)
boxes_items.append(self.label_2)
boxes_items.append(self.label_3)
#=================================== Calling =======================
self.BrowesImageButton.clicked.connect(self.setImage)
self.checkBox_Short.stateChanged.connect(self.Change_the_Checkbox_Short_Function)
self.checkBox_Long.stateChanged.connect(self.Change_the_Checkbox_Long_Function)
#=================================== Functions =========================
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Cropping"))
self.BrowesImageButton.setText(_translate("Dialog", "Select Image"))
self.groupBox.setTitle(_translate("Dialog", "Choose Plate Type"))
self.checkBox_Short.setText(_translate("Dialog", "Short Plate"))
self.checkBox_Long.setText(_translate("Dialog", "Long Plate"))
self.SegmentImageButton.setText(_translate("Dialog", "Segment Image"))
self.label.setToolTip(_translate("Dialog", "Drage it on first charecter"))
self.label_2.setToolTip(_translate("Dialog", "Drage it on second charecter"))
self.label_3.setToolTip(_translate("Dialog", "Drage it on third charecter"))
#=================================================================================
def setImage(self):
fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select Image", "", "Image Files (*.png *.jpg *jpeg *.bmp)") # Ask for file
if fileName: # If the user gives a file
pixmap = QtGui.QPixmap(fileName) # Setup pixmap with the provided image
pixmap = pixmap.scaled(self.UserImageLbl.width(), self.UserImageLbl.height(), QtCore.Qt.KeepAspectRatio) # Scale pixmap
self.UserImageLbl.setPixmap(pixmap) # Set the pixmap onto the label
self.UserImageLbl.setAlignment(QtCore.Qt.AlignCenter) # Align the label to center
#UserImageLbl = DropLabel()
self.checkBox_Short.setEnabled(True)
self.checkBox_Long.setEnabled(True)
#=====================================================================
def Change_the_Checkbox_Short_Function(self):
if self.checkBox_Short.isChecked():
self.checkBox_Long.setEnabled(False)
self.SegmentImageButton.setEnabled(True)
# Presenting 3 boxes 45x45 hear
for box_item in boxes_items:
#box_item.setDragEnabled(True)
box_item.setMinimumSize(QtCore.QSize(45, 45))
box_item.setMaximumSize(QtCore.QSize(45, 45))
box_item.show()
box_item = DraggableLabel()
else:
self.checkBox_Long.setEnabled(True)
for box_item in boxes_items:
box_item.hide()
#========================================================================
def Change_the_Checkbox_Long_Function(self):
if self.checkBox_Long.isChecked():
self.checkBox_Short.setEnabled(False)
self.SegmentImageButton.setEnabled(True)
# Presenting 3 boxes 40x40 hear
for box_item in boxes_items:
# box_item.setDragEnabled(True)
box_item.setMinimumSize(QtCore.QSize(40, 40))
box_item.setMaximumSize(QtCore.QSize(40, 40))
box_item.show()
box_item = DraggableLabel()
#for box_item in Sboxes_items:
#DraggableLabel(box_item)
else:
self.checkBox_Short.setEnabled(True)
for box_item in boxes_items:
box_item.hide()
#==========================================================================
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
I hope I can find someone who can help me with that.
Thanks in advance.
I believe you are a bit confused about how drag and drop works, but the most important thing is that you don't need "actual" drag and drop for what you want to achieve.
In this example I added the draggable boxes instead of the labels, and they are free to be moved within the image rectangle. I had to do some modifications to your original code, because it was a bit confusing and had some logic that simply didn't work.
class DraggableLabel(QLabel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setStyleSheet("border-color: rgb(238, 0, 0); border-width : 2.0px; border-style:inset; background: transparent;")
self.origin = None
def setLimits(self, rect):
self.limits = rect
def mousePressEvent(self, event):
if not self.origin:
# update the origin point, we'll need that later
self.origin = self.pos()
if event.button() == Qt.LeftButton:
self.mousePos = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton:
# move the box
self.move(self.pos() + event.pos() - self.mousePos)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
# if the box is not within the image boundaries, move it
# back to the original position
if not self.limits.contains(self.geometry()):
self.move(self.origin)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.setEnabled(True)
Dialog.resize(1050, 800)
Dialog.setMinimumSize(QtCore.QSize(1050, 800))
Dialog.setMaximumSize(QtCore.QSize(1050, 800))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../.designer/backup/project pic/images LPR icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
Dialog.setStyleSheet("background-color: rgb(217, 217, 217);\n"
"background-color: rgb(243, 243, 243);")
# Dialog.setAcceptDrops(True)
self.BrowesImageButton = QtWidgets.QPushButton(Dialog)
self.BrowesImageButton.setGeometry(QtCore.QRect(820, 60, 200, 60))
self.BrowesImageButton.setMinimumSize(QtCore.QSize(200, 60))
self.BrowesImageButton.setMaximumSize(QtCore.QSize(200, 60))
font = QtGui.QFont()
font.setFamily("Microsoft YaHei UI")
font.setPointSize(11)
font.setBold(True)
font.setWeight(75)
self.BrowesImageButton.setFont(font)
self.BrowesImageButton.setStyleSheet("")
self.BrowesImageButton.setCheckable(True)
self.BrowesImageButton.setObjectName("BrowesImageButton")
self.groupBox = QtWidgets.QGroupBox(Dialog)
self.groupBox.setGeometry(QtCore.QRect(820, 170, 211, 131))
font = QtGui.QFont()
font.setFamily("Microsoft YaHei")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.groupBox.setFont(font)
self.groupBox.setLayoutDirection(QtCore.Qt.LeftToRight)
self.groupBox.setObjectName("groupBox")
self.checkBox_Short = QtWidgets.QCheckBox(self.groupBox)
self.checkBox_Short.setGeometry(QtCore.QRect(20, 40, 141, 23))
font = QtGui.QFont()
font.setFamily("Adobe Heiti Std R")
font.setPointSize(10)
self.checkBox_Short.setFont(font)
self.checkBox_Short.setLayoutDirection(QtCore.Qt.LeftToRight)
self.checkBox_Short.setObjectName("checkBox_Short")
self.checkBox_Short.setEnabled(False)
self.checkBox_Long = QtWidgets.QCheckBox(self.groupBox)
self.checkBox_Long.setGeometry(QtCore.QRect(20, 80, 141, 23))
font = QtGui.QFont()
font.setFamily("Adobe Heiti Std R")
font.setPointSize(10)
self.checkBox_Long.setFont(font)
self.checkBox_Long.setLayoutDirection(QtCore.Qt.LeftToRight)
self.checkBox_Long.setObjectName("checkBox_Long")
self.checkBox_Long.setEnabled(False)
self.SegmentImageButton = QtWidgets.QPushButton(Dialog)
self.SegmentImageButton.setGeometry(QtCore.QRect(830, 330, 200, 60))
self.SegmentImageButton.setMinimumSize(QtCore.QSize(200, 60))
self.SegmentImageButton.setMaximumSize(QtCore.QSize(200, 60))
font = QtGui.QFont()
font.setFamily("Microsoft YaHei UI")
font.setPointSize(11)
font.setBold(True)
font.setWeight(75)
self.SegmentImageButton.setFont(font)
self.SegmentImageButton.setStyleSheet("")
self.SegmentImageButton.setCheckable(True)
self.SegmentImageButton.setObjectName("SegmentImageButton")
self.SegmentImageButton.setEnabled(False)
self.UserImageLbl = QtWidgets.QLabel(Dialog)
self.UserImageLbl.setGeometry(QtCore.QRect(40, 40, 750, 500))
self.UserImageLbl.setMinimumSize(QtCore.QSize(750, 500))
self.UserImageLbl.setMaximumSize(QtCore.QSize(750, 500))
self.UserImageLbl.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.UserImageLbl.setFrameShadow(QtWidgets.QFrame.Plain)
self.UserImageLbl.setLineWidth(1)
self.UserImageLbl.setMidLineWidth(0)
self.UserImageLbl.setText("")
self.UserImageLbl.setScaledContents(False)
self.UserImageLbl.setAlignment(QtCore.Qt.AlignCenter)
self.UserImageLbl.setObjectName("UserImageLbl")
self.buttonGroup = QButtonGroup()
self.buttonGroup.addButton(self.checkBox_Short)
self.buttonGroup.addButton(self.checkBox_Long)
self.label_1 = DraggableLabel(Dialog)
self.label_2 = DraggableLabel(Dialog)
self.label_3 = DraggableLabel(Dialog)
self.label_1.move(820, 470)
self.label_2.move(900, 470)
self.label_3.move(980, 470)
self.labels = [self.label_1, self.label_2, self.label_3]
for label in self.labels:
label.hide()
label.raise_()
self.BrowesImageButton.clicked.connect(self.setImage)
self.checkBox_Long.toggled.connect(self.setBoxSizes)
self.checkBox_Short.toggled.connect(self.setBoxSizes)
def setImage(self):
fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select Image", "", "Image Files (*.png *.jpg *jpeg *.bmp)") # Ask for file
if fileName: # If the user gives a file
pixmap = QtGui.QPixmap(fileName) # Setup pixmap with the provided image
pixmap = pixmap.scaled(self.UserImageLbl.width(), self.UserImageLbl.height(), QtCore.Qt.KeepAspectRatio) # Scale pixmap
self.UserImageLbl.setPixmap(pixmap) # Set the pixmap onto the label
self.UserImageLbl.setAlignment(QtCore.Qt.AlignCenter) # Align the label to center
#UserImageLbl = DropLabel()
self.checkBox_Short.setEnabled(True)
self.checkBox_Long.setEnabled(True)
def setBoxSizes(self):
if self.checkBox_Short.isChecked():
boxSize = 40
else:
boxSize = 45
for label in self.labels:
label.setFixedSize(boxSize, boxSize)
label.setLimits(self.UserImageLbl.geometry())
label.show()
I want to add one functionality in my application when update is done then data in pyqt5 table should automatically refreshed with the new data in search results. But when I click the buttom, there is nothing happened.
# -*- coding: utf-8 -*-
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import logging
import logging.config
import time
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QIcon('images/icon.png'))
Control_system.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}")
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
#表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0,0,QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0,1,QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0,2,QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0,3, QTableWidgetItem("温度值"))
self.tableWidget.setItem(0,4, QTableWidgetItem("电流值"))
self.tableWidget.setItem(0,5, QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0,0).setFont(font)
self.tableWidget.item(0,1).setFont(font)
self.tableWidget.item(0,2).setFont(font)
self.tableWidget.item(0,3).setFont(font)
self.tableWidget.item(0,4).setFont(font)
self.tableWidget.item(0,5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.slotStart)
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
def slotStart(self):
#开始按钮不可点击,线程开始
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData()
self.update_data_thread.update_data.connect(self.set_btn)
self.update_data_thread.start()
def set_btn(self):
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):#使用qt自己本身的线程
update_data=QtCore.pyqtSignal()#因为这个信号槽要继承于Qobject,不然会发生没有emit,connect函数的报错,括号里面填写的是发射的数据类型
#print(".............")
def __init__(self):
super().__init__()
def run(self):
cnt = 0
while True:
cnt += 1
self.tableWidget.setItem(2,2,QTableWidgetItem(cnt))
self.update_data.emit() # 发射信号
time.sleep(1)
if __name__ == '__main__':
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Control_system()
ui.setupUi(MainWindow) # 将ui实例绘制到窗口实例上
desktop = QtWidgets.QApplication.desktop()
x = (desktop.width() - MainWindow.width()) // 2
y = (desktop.height() - MainWindow.height()) // 2
MainWindow.move(x,y)
MainWindow.show()
sys.exit(app.exec())#exec_()方法的作用是“进入程序的主循环直到exit()被调
You cannot and should not modify the GUI directly from another thread, in your case QTableWidget and QTableWidgetItem are part of the GUI so the code: self.tableWidget.setItem(2, 2, QTableWidgetItem(cnt)) is incorrect. What should be done is to send the information to the main thread through elements that are thread-safe such as signals, QEvents, etc.
On the other hand PyQt recommends not modifying the class it generates but creating a widget and using the generated class as an interface(1).
Considering the above the solution is:
import sys
import time
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QtGui.QIcon("images/icon.png"))
Control_system.setStyleSheet(
"QMainWindow{border-image:url(images/background.jpg)}"
)
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
# 表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0, 2, QtWidgets.QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0, 3, QtWidgets.QTableWidgetItem("温度值"))
self.tableWidget.setItem(0, 4, QtWidgets.QTableWidgetItem("电流值"))
self.tableWidget.setItem(0, 5, QtWidgets.QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0, 0).setFont(font)
self.tableWidget.item(0, 1).setFont(font)
self.tableWidget.item(0, 2).setFont(font)
self.tableWidget.item(0, 3).setFont(font)
self.tableWidget.item(0, 4).setFont(font)
self.tableWidget.item(0, 5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
#QtCore.pyqtSlot()
def slotStart(self):
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData(self)
self.update_data_thread.dataChanged.connect(self.onDataChanged)
self.update_data_thread.start()
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while True:
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
if __name__ == "__main__":
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
w = Control_system()
w.show()
sys.exit(app.exec_())
Update:
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
self.pushButton_2.clicked.connect(self.slotStop)
#QtCore.pyqtSlot()
def slotStart(self):
# ...
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
#QtCore.pyqtSlot()
def slotStop(self):
self.update_data_thread.requestInterruption()
self.update_data_thread.quit()
self.update_data_thread.wait()
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while not self.isInterruptionRequested(): # <---
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
(1) Using the Generated Code
What I'm doing is about that when I clicked the date of the
calendar ,then it will display the class of UI_tab which is a tabwidget ,including two tabs.each tab includes some labels and others.However it
cant't work.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Tab(object):
# create tabwidget
def __init__(self,parentw,*args):
print(args)
print(parentw)
super().__init__()
self.font = QtGui.QFont()
self.font.setFamily("仿宋")
self.font.setPointSize(10)
self.font.setItalic(False)
self.font.setUnderline(False)
self.w=['title0','title1',
'creator0','creator1',
'c_time0','c_time1',
'user0','user1',
'd_time0','d_time1',
'detail0']
self.wt=['title','creator','create_time',
'viewer','finish_time','detail']
self.tabWidget = QtWidgets.QTabWidget(parentw)
self.tabWidget.setGeometry(QtCore.QRect(50, 10, 500, 2500))
self.tabWidget.setMinimumSize(QtCore.QSize(400, 400))
self.tabWidget.setTabsClosable(False)
self.tabWidget.setMovable(True)
self.tabWidget.setObjectName("tabWidget")
self.initTab()
# create tabs in tabwidget
def initTab(self,tabnum=2):
self.tabnum=tabnum
print('inittab')
self.tabs={}
for i in range(self.tabnum):
self.tabs[str(i)]=QtWidgets.QWidget()
self.tabs[str(i)].setObjectName("tab"+str(i))
self.tabWidget.addTab(self.tabs[str(i)], "")
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabs[str(i)]),str(i))
self.initw_in_tab(self.tabs[str(i)])
print(self.tabs)
# add labels,textbrowser in tabs
def initw_in_tab(self,parentw):
w_in_tab={}
print('initw_in_tab')
for i in self.w:
w_in_tab[i]=QtWidgets.QLabel(parentw)
w_in_tab[i].setFont(self.font)
w_in_tab[i].setLayoutDirection(QtCore.Qt.LeftToRight)
w_in_tab[i].setAutoFillBackground(False)
w_in_tab[i].setFrameShape(QtWidgets.QFrame.Box)
w_in_tab[i].setFrameShadow(QtWidgets.QFrame.Raised)
w_in_tab[i].setLineWidth(1)
w_in_tab[i].setMidLineWidth(0)
w_in_tab[i].setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
w_in_tab[i].setIndent(3)
w_in_tab[i].setObjectName(i)
if self.w.index(i)%2 ==0:
w_in_tab[i].setGeometry(QtCore.QRect(20, 180 + self.w.index(i)*25, 59, 25))
w_in_tab[i].setText(self.wt[int(self.w.index(i)/2)])
else:
w_in_tab[i].setGeometry(QtCore.QRect(140, 180 +(self.w.index(i)-1)*25, 59, 25))
scrollArea = QtWidgets.QScrollArea(parentw)
scrollArea.setEnabled(True)
scrollArea.setGeometry(QtCore.QRect(140, 7*25+180, 341, 440))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(scrollArea.sizePolicy().hasHeightForWidth())
scrollArea.setSizePolicy(sizePolicy)
scrollArea.setMinimumSize(QtCore.QSize(200, 100))
scrollArea.setWidgetResizable(True)
scrollArea.setObjectName("scrollArea")
scrollAreaWidgetContents_2 = QtWidgets.QWidget()
scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 322, 1600))
scrollAreaWidgetContents_2.setMinimumSize(QtCore.QSize(200, 1600))
scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2")
detail2 = QtWidgets.QTextBrowser(scrollAreaWidgetContents_2)
detail2.setGeometry(QtCore.QRect(0, 0, 321, 600))
detail2.setMinimumSize(QtCore.QSize(296, 192))
detail2.setObjectName("detail2")
scrollArea.setWidget(scrollAreaWidgetContents_2)
class Ui_MainWindow(object):
# setup main ui include calendar
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(997, 707)
MainWindow.setStyleSheet("")
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.centralWidget.setUpdatesEnabled(True)
self.calendarw = QtWidgets.QWidget(self.centralWidget)
self.calendarw.setGeometry(QtCore.QRect(560, 20, 361, 541))
self.calendarw.setObjectName("calendarw")
self.cal = QtWidgets.QCalendarWidget(self.calendarw)
self.cal.setGeometry(QtCore.QRect(0, 60, 361, 481))
self.cal.setFirstDayOfWeek(QtCore.Qt.Monday)
self.cal.setObjectName("cal")
self.cal_la = QtWidgets.QLabel(self.calendarw)
self.cal_la.setGeometry(QtCore.QRect(110, 20, 161, 31))
font = QtGui.QFont()
font.setPointSize(22)
self.cal_la.setFont(font)
self.cal_la.setAlignment(QtCore.Qt.AlignCenter)
self.cal_la.setObjectName("cal_la")
MainWindow.setCentralWidget(self.centralWidget)
MainWindow.setWindowTitle("MainWindow")
self.cal_la.setText("calendar")
#
# Ui_Tab(self.centralWidget)
# this makes me confused,I hope that when I clicked the date of the
# calendar ,then it will display the class of UI_tab.However it
# cant't work.
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
QtCore.QMetaObject.connectSlotsByName(MainWindow)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
when I use the below code , it exactly does what I want it to do, but without clicking the calendar date.
Ui_Tab(self.centralWidget)
instead of
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
visit PyQt Window No Show
I just change the code below
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
to
self.cal.clicked.connect(Ui_Tab(self.centralWidget).show)
I am a qt noob and I am trying to build an application that needs to display the following:
a list of e-mail (which I am displaying in column 1 of a grid layout
with a QListWidget1 left list)
a list of passwords (which I display in column 2 of grid layout in a QListWidget2 middle list)
Now, I would like to display a list of button (1 for every element of the list) which is supposed to copy the password in the QListWidget2.
Should I just loop in column 3 and add a push button for every row? Or is there a better way of doing this? Is there an object that could help me by laying out the buttons already in line with the elements of my list, so that I can connect them easily with the value of every entry in the list (for copying them later)?
My code is the following:
from PySide import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(311, 499)
self.gridLayoutWidget = QtGui.QWidget(Dialog)
self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 291, 371))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout = QtGui.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
# self.dockWidget = QtGui.QDockWidget(self.gridLayoutWidget)
# self.dockWidget.setObjectName("dockWidget")
# self.dockWidgetContents = QtGui.QWidget()
# self.dockWidgetContents.setObjectName("dockWidgetContents")
# self.dockWidget.setWidget(self.dockWidgetContents)
# self.gridLayout.addWidget(self.dockWidget, 0, 0, 1, 1)
self.leftList = QtGui.QListWidget(self.gridLayoutWidget)
self.gridLayout.addWidget(self.leftList, 0, 0, 1, 1)
self.middleList = QtGui.QListWidget(self.gridLayoutWidget)
self.gridLayout.addWidget(self.middleList, 0, 1, 1, 1)
self.rightList = QtGui.QListWidget(self.gridLayoutWidget)
self.gridLayout.addWidget(self.rightList, 0, 2, 1, 1)
self.progressBar = QtGui.QProgressBar(Dialog)
self.progressBar.setGeometry(QtCore.QRect(10, 410, 231, 23))
self.progressBar.setInputMethodHints(QtCore.Qt.ImhNone)
self.progressBar.setMaximum(30)
self.progressBar.setProperty("value", 30)
self.progressBar.setInvertedAppearance(False)
self.progressBar.setTextDirection(QtGui.QProgressBar.TopToBottom)
self.progressBar.setObjectName("progressBar")
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(240, 413, 51, 16))
self.label.setObjectName("label")
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(10, 440, 291, 51))
self.pushButton.setObjectName("pushButton")
self.line = QtGui.QFrame(Dialog)
self.line.setGeometry(QtCore.QRect(10, 390, 291, 20))
self.line.setFrameShape(QtGui.QFrame.HLine)
self.line.setFrameShadow(QtGui.QFrame.Sunken)
self.line.setObjectName("line")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.progressBar.setFormat(QtGui.QApplication.translate("Dialog", "%vs", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "TimeOut", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("Dialog", "Refresh", None, QtGui.QApplication.UnicodeUTF8))
If you want to add a button for each item in the list, you can use setItemWidget.
To get the buttons to align to the right, use a layout as in the demo script below:
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.list = QtGui.QListWidget(self)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.list)
def addListItem(self, text):
item = QtGui.QListWidgetItem(text)
self.list.addItem(item)
widget = QtGui.QWidget(self.list)
button = QtGui.QToolButton(widget)
layout = QtGui.QHBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
layout.addStretch()
layout.addWidget(button)
self.list.setItemWidget(item, widget)
button.clicked[()].connect(
lambda: self.handleButtonClicked(item))
def handleButtonClicked(self, item):
print(item.text())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
for label in 'red blue green yellow purple'.split():
window.addListItem(label)
window.setGeometry(500, 300, 300, 200)
window.show()
sys.exit(app.exec_())
I wanted to have a total of 8 groupbox in the Dialog box. I don't know how to associate the horizontal scrollbar so that I can scroll it down and access all the group box. In the code below I have added only 2 as an example. Any help is appreciated.
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(300, 20, 81, 71))
self.buttonBox.setOrientation(QtCore.Qt.Vertical)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.scrollArea = QtGui.QScrollArea(Dialog)
self.scrollArea.setGeometry(QtCore.QRect(30, 20, 251, 251))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 249, 249))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.groupBox = QtGui.QGroupBox(self.scrollAreaWidgetContents)
self.groupBox.setGeometry(QtCore.QRect(10, 10, 211, 81))
self.groupBox.setObjectName("groupBox")
self.textEdit = QtGui.QTextEdit(self.groupBox)
self.textEdit.setGeometry(QtCore.QRect(10, 20, 171, 51))
self.textEdit.setObjectName("textEdit")
self.groupBox_2 = QtGui.QGroupBox(self.scrollAreaWidgetContents)
self.groupBox_2.setGeometry(QtCore.QRect(10, 110, 211, 111))
self.groupBox_2.setObjectName("groupBox_2")
self.textEdit_2 = QtGui.QTextEdit(self.groupBox_2)
self.textEdit_2.setGeometry(QtCore.QRect(10, 20, 171, 84))
self.textEdit_2.setObjectName("textEdit_2")
self.verticalScrollBar = QtGui.QScrollBar(self.scrollAreaWidgetContents)
self.verticalScrollBar.setGeometry(QtCore.QRect(230, 0, 16, 241))
self.verticalScrollBar.setOrientation(QtCore.Qt.Vertical)
self.verticalScrollBar.setObjectName("verticalScrollBar")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setTitle(QtGui.QApplication.translate("Dialog", "GroupBox", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_2.setTitle(QtGui.QApplication.translate("Dialog", "GroupBox", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
As I said in the comments, QScrollArea doesn't need manual QScrollBar. It will create when needed. I can't be sure what your problem is without seeing the 'not working' code, but my guess is the fixed sized items and their placement. You are probably putting things outside of the widgets margin or overlapping each other so that the inner widget does not grow appropriately.
Anyway, here is a minimal example that replicates your dialog (notice the scrollbar):
import sys
from PyQt4 import QtGui, QtCore
class MyDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
scrolllayout = QtGui.QVBoxLayout()
scrollwidget = QtGui.QWidget()
scrollwidget.setLayout(scrolllayout)
scroll = QtGui.QScrollArea()
scroll.setWidgetResizable(True) # Set to make the inner widget resize with scroll area
scroll.setWidget(scrollwidget)
self.groupboxes = [] # Keep a reference to groupboxes for later use
for i in range(8): # 8 groupboxes with textedit in them
groupbox = QtGui.QGroupBox('%d' % i)
grouplayout = QtGui.QHBoxLayout()
grouptext = QtGui.QTextEdit()
grouplayout.addWidget(grouptext)
groupbox.setLayout(grouplayout)
scrolllayout.addWidget(groupbox)
self.groupboxes.append(groupbox)
self.buttonbox = QtGui.QDialogButtonBox()
self.buttonbox.setOrientation(QtCore.Qt.Vertical)
self.buttonbox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
layout = QtGui.QHBoxLayout()
layout.addWidget(scroll)
layout.addWidget(self.buttonbox)
self.setLayout(layout)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog = MyDialog()
dialog.show()
sys.exit(app.exec_())