adding and removing widgets in PyQt - python

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)

Related

I have two files LOGIN.py and LOGINCLICK.py. How to open LOGIN.py file from LOGINCLICK.py by clicking a button?

LOGIN.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_LOGIN_PAGE(object):
def setupUi(self, LOGIN_PAGE):
LOGIN_PAGE.setObjectName("LOGIN_PAGE")
LOGIN_PAGE.resize(1909, 995)
self.centralwidget = QtWidgets.QWidget(LOGIN_PAGE)
self.centralwidget.setObjectName("centralwidget")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(690, 220, 501, 571))
font = QtGui.QFont()
font.setFamily("Cambria Math")
font.setPointSize(11)
self.frame.setFont(font)
self.frame.setStyleSheet("QFrame{\n""background:rgb(255, 250, 175);\n""border-radius:30px;\n"
"}\n""\n""QLineEdit{\n""border-radius:10px;\n""}\n""\n""QPushButton{\n""background:#03a9f4;\n"
"border-radius:10px;}")
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.pushButton = QtWidgets.QPushButton(self.frame)
self.pushButton.setGeometry(QtCore.QRect(30, 360, 441, 81))
font = QtGui.QFont()
font.setFamily("Cambria")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.frame)
self.pushButton_2.setGeometry(QtCore.QRect(130, 480, 241, 41))
font = QtGui.QFont()
font.setFamily("Gill Sans MT")
font.setPointSize(10)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.lineEdit = QtWidgets.QLineEdit(self.frame)
self.lineEdit.setGeometry(QtCore.QRect(30, 260, 441, 51))
font = QtGui.QFont()
font.setFamily("Cambria Math")
font.setPointSize(12)
self.lineEdit.setFont(font)
self.lineEdit.setText("")
self.lineEdit.setEchoMode(QtWidgets.QLineEdit.Password)
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.frame)
self.lineEdit_2.setGeometry(QtCore.QRect(30, 110, 441, 51))
font = QtGui.QFont()
font.setFamily("Cambria Math")
font.setPointSize(12)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.label = QtWidgets.QLabel(self.frame)
self.label.setGeometry(QtCore.QRect(40, 60, 231, 41))
font = QtGui.QFont()
font.setFamily("Cambria Math")
font.setPointSize(11)
self.label.setFont(font)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.frame)
self.label_2.setGeometry(QtCore.QRect(40, 210, 231, 41))
font = QtGui.QFont()
font.setFamily("Cambria Math")
font.setPointSize(11)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
LOGIN_PAGE.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(LOGIN_PAGE)
self.statusbar.setObjectName("statusbar")
LOGIN_PAGE.setStatusBar(self.statusbar)
self.retranslateUi(LOGIN_PAGE)
QtCore.QMetaObject.connectSlotsByName(LOGIN_PAGE)
def retranslateUi(self, LOGIN_PAGE):
_translate = QtCore.QCoreApplication.translate
LOGIN_PAGE.setWindowTitle(_translate("LOGIN_PAGE", "MainWindow"))
self.pushButton.setText(_translate("LOGIN_PAGE", "LOGIN"))
self.pushButton_2.setText(_translate("LOGIN_PAGE", "Forget Password"))
self.lineEdit.setPlaceholderText(_translate("LOGIN_PAGE", "PASSWORD"))
self.lineEdit_2.setPlaceholderText(_translate("LOGIN_PAGE", "USERNAME"))
self.label.setText(_translate("LOGIN_PAGE", "USERNAME :"))
self.label_2.setText(_translate("LOGIN_PAGE", "PASSWORD :"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
LOGIN_PAGE = QtWidgets.QMainWindow()
ui = Ui_LOGIN_PAGE()
ui.setupUi(LOGIN_PAGE)
LOGIN_PAGE.show()
sys.exit(app.exec_())
LOGINCLICK.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(505, 256)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(-1, -1, 501, 251))
self.frame.setStyleSheet("QFrame{\n""background:rgb(248, 255, 185);}\n""\n""QPushButton{\n"
"background:#03a9f4;\n""border-radius:10px;}")
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.pushButton1 = QtWidgets.QPushButton(self.frame)
self.pushButton1.setGeometry(QtCore.QRect(70, 90, 151, 51))
self.pushButton1.setObjectName("pushButton1")
self.pushButton1_2 = QtWidgets.QPushButton(self.frame)
self.pushButton1_2.setGeometry(QtCore.QRect(280, 90, 151, 51))
self.pushButton1_2.setObjectName("pushButton1_2")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton1.setText(_translate("MainWindow", "LOGIN"))
self.pushButton1_2.setText(_translate("MainWindow", "REGISTRATION"))
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_())
How to switch from LOGINCLICK.py to LOGIN.py by clicking a button?
First of all, and this is more a matter of concept, you're not going to "switch" between those files, but between the instances of the classes that are in those files.
Second, you should create a file that acts as a "main" script, which is the file that you'll actually run from python; this is a general rule for programs that use multiple files as "modules", and is almost mandatory for PyQt when using files generated by pyuic; note that you should also never modify the contents of those files, but import them as python modules (read more about using Designer).
Recreate the files with pyuic, then create a new file that will look like this:
from PyQt5 import QtWidgets
from LOGINCLICK import Ui_MainWindow
from LOGIN import Ui_LOGIN_PAGE
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton1.clicked.connect(self.showLogin)
def showLogin(self):
self.loginWindow = LoginWindow()
self.loginWindow.show()
class LoginWindow(QtWidgets.QMainWindow, Ui_LOGIN_PAGE):
def __init__(self):
super().__init__()
self.setupUi(self)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
Now, some suggestions:
avoid fixed geometries in any case, and use layout managers instead (like QGridLayout, QHBoxLayout or QVBoxLayout) so that the contents of the windows will always adjust to the available size, otherwise some of the widgets might become unaccessible if the user resizes the window to a smaller size than you decided (there are also other reasons for this, but this is the most important);
don't use uppercase names for files or variables; read more about naming conventions in the Style Guide for Python Code;
a login window should probably be "modal" (shown over the current windows and avoiding interaction with them until the login window is closed); you can use a QDialog for this: from Designer create a new empty dialog, copy the elements of your current login form and paste them to the new dialog (or select all of them and use ctrl+drag), save and generate the file with pyuic, then change the above code considering the following modifications:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
#...
def showLogin(self):
self.loginWindow = LoginWindow(self)
self.loginWindow.exec_()
class LoginWindow(QtWidgets.QDialog, Ui_LOGIN_PAGE):
def __init__(self, parent=None):
super().__init__()
self.setupUi(self)

How to get Icon size to completely fill PushButton/be rescalable in PyQt5 python

I have a class called TwoStateButton which inherits QPushButton so that the icon can change when the button is being clicked on and so the icon gets resized in proportion to the button when the whole window gets resized.
When I run this code, the button takes up the whole window and the icon is about 10% of the button. I'm trying to get it so that the icon image takes up the entire pushbutton and that they both get resized by the same amount when the window is resized.
What modifications to my code should I do to achieve this?
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class TwoStateButton(QtWidgets.QPushButton):
def __init__(self, on, hover, parent=None):
super(TwoStateButton, self).__init__(parent)
self.pad = 4 # padding between the icon and the button frame
self.minSize = 8 # minimum size of the icon
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
)
self.setSizePolicy(sizePolicy)
self.setIcon(QtGui.QIcon(on))
self.on = on
self.hover = hover
def mousePressEvent(self, event):
super(TwoStateButton, self).mousePressEvent(event)
self.setIcon(QtGui.QIcon(self.hover))
def mouseReleaseEvent(self, event):
super(TwoStateButton, self).mouseReleaseEvent(event)
self.setIcon(QtGui.QIcon("%s" % (self.on)))
def paintEvent(self, event):
qp = QtGui.QPainter(self)
opt = QtWidgets.QStyleOptionButton()
self.initStyleOption(opt)
r = opt.rect
h = r.height()
w = r.width()
iconSize = max(min(h, w) - 2 * self.pad, self.minSize)
opt.iconSize = QtCore.QSize(iconSize, iconSize)
self.style().drawControl(QtWidgets.QStyle.CE_PushButton, opt, qp,self)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1090, 681)
MainWindow.setStyleSheet("")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton_2 = TwoStateButton(
"images/Button5-3.png", "images/Button5-4.png", self.centralwidget
)
self.pushButton_2.setGeometry(QtCore.QRect(430, 310, 141, 81))
self.pushButton_2.setText("")
self.pushButton_2.setCheckable(False)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1090, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setStyleSheet(
"border-image: url(:/images/Button5-3.png)"
)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
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_())

How to make the bottom row of QGridLayout automatically fill the window's size in PyQt5?

As the window changes its size, I want to the bottom of the row, which is a QSplitter including 3 widgets, to expand and fill the remaining window while the widgets in the first row keep the original y-position. How to do that?
If the three widgets in QSplitter can keep their former ratio, it'll be better.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.MainWindow=MainWindow
self.MainWindow.setObjectName("self.MainWindow")
self.MainWindow.resize(850, 800)
self.centralwidget = QtWidgets.QWidget(self.MainWindow)
self.MainWindow.setCentralWidget(self.centralwidget)
self.vlayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setText("LABEL")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.gridLayout.addWidget(self.label,0,0,1,1)
self.gridLayout.addWidget(self.comboBox,0,1,1,9)
"""table """
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
"""tab1"""
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setMinimumHeight(50)
"""tab2"""
self.tabWidget_2 = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget_2.setMinimumHeight(50)
"""splitter window"""
splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
splitter.addWidget(self.tableWidget)
splitter.addWidget(self.tabWidget)
splitter.addWidget(self.tabWidget_2)
splitter.setSizes([232,225,225])
self.gridLayout.addWidget(splitter,3,0,5,10)
self.gridLayout.setRowMinimumHeight(3,690)
self.vlayout.addLayout(self.gridLayout)
spacerItem = QtWidgets.QSpacerItem(20, 245, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.vlayout.addItem(spacerItem)
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_())
I want to the QSplitter to expand to the bottom of the window.

How can I draw inside existing QGraphicsVIew?

just like the title says i'm trying to draw inside an existing QGraphicsView. The window I generated using QT Designer, and I would like to draw a matrix of 16x16 squares inside the QGraphicsView.
This is the code I have as of right now:
Window:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(911, 567)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 10, 301, 31))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(620, 40, 271, 91))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.groupBox.setFont(font)
self.groupBox.setObjectName("groupBox")
self.rdtest = QtWidgets.QRadioButton(self.groupBox)
self.rdtest.setGeometry(QtCore.QRect(60, 60, 101, 22))
self.rdtest.setObjectName("rdtest")
self.rdtrain = QtWidgets.QRadioButton(self.groupBox)
self.rdtrain.setGeometry(QtCore.QRect(60, 30, 101, 22))
self.rdtrain.setObjectName("rdtrain")
self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(10, 40, 601, 411))
self.graphicsView.setObjectName("graphicsView")
self.clear = QtWidgets.QPushButton(self.centralwidget)
self.clear.setGeometry(QtCore.QRect(10, 470, 88, 29))
self.clear.setObjectName("clear")
self.trainNewInput = QtWidgets.QPushButton(self.centralwidget)
self.trainNewInput.setGeometry(QtCore.QRect(500, 470, 111, 29))
self.trainNewInput.setObjectName("trainNewInput")
self.trainbox = QtWidgets.QGroupBox(self.centralwidget)
self.trainbox.setGeometry(QtCore.QRect(620, 150, 271, 171))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.trainbox.setFont(font)
self.trainbox.setObjectName("trainbox")
self.vtrain = QtWidgets.QLineEdit(self.trainbox)
self.vtrain.setGeometry(QtCore.QRect(100, 70, 101, 29))
self.vtrain.setObjectName("vtrain")
self.label_2 = QtWidgets.QLabel(self.trainbox)
self.label_2.setGeometry(QtCore.QRect(40, 70, 56, 31))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.trainDefault = QtWidgets.QPushButton(self.trainbox)
self.trainDefault.setGeometry(QtCore.QRect(40, 30, 161, 29))
self.trainDefault.setObjectName("trainDefault")
self.output = QtWidgets.QLabel(self.trainbox)
self.output.setGeometry(QtCore.QRect(10, 130, 271, 17))
self.output.setText("")
self.output.setObjectName("output")
self.output_2 = QtWidgets.QLabel(self.trainbox)
self.output_2.setGeometry(QtCore.QRect(10, 150, 271, 17))
self.output_2.setText("")
self.output_2.setObjectName("output_2")
self.testbox = QtWidgets.QGroupBox(self.centralwidget)
self.testbox.setGeometry(QtCore.QRect(620, 330, 271, 171))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.testbox.setFont(font)
self.testbox.setObjectName("testbox")
self.pushButton = QtWidgets.QPushButton(self.testbox)
self.pushButton.setGeometry(QtCore.QRect(50, 40, 161, 29))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 911, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "RNA: Numeros "))
self.groupBox.setTitle(_translate("MainWindow", "Opciones:"))
self.rdtest.setText(_translate("MainWindow", "Test"))
self.rdtrain.setText(_translate("MainWindow", "Train"))
self.clear.setText(_translate("MainWindow", "Clear"))
self.trainNewInput.setText(_translate("MainWindow", "Train new Input"))
self.trainbox.setTitle(_translate("MainWindow", "Train:"))
self.label_2.setText(_translate("MainWindow", "% Test:"))
self.trainDefault.setText(_translate("MainWindow", "Train Default Data"))
self.testbox.setTitle(_translate("MainWindow", "Test:"))
self.pushButton.setText(_translate("MainWindow", "Start Test"))
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_())
Logic class where I want to create a method that draws on the QGraphicsView from the window:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QGraphicsScene
from PyQt5.QtCore import (QLineF, QPointF, QRectF, Qt)
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtWidgets import (QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem,
QGridLayout, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton)
from window import Ui_MainWindow
from RNA import NumberIA
train = []
train_r = []
test = []
test_r = []
class MyFirstGuiProgram(Ui_MainWindow):
def __init__(self, dialog):
Ui_MainWindow.__init__(self)
self.setupUi(dialog)
self.rdtrain.setChecked(True)
# Connect "add" button with a custom function (addInputTextToListbox)
self.clear.clicked.connect(self.addInputTextToListbox)
self.trainDefault.clicked.connect(self.t_DefaultData)
self.rdtest.clicked.connect(self.enableTest)
self.rdtrain.clicked.connect(self.enableTrain)
def enableTest(self):
self.trainbox.setEnabled(False)
self.trainNewInput.setEnabled(False)
self.testbox.setEnabled(True)
def drawSomething(self):
tes = "f"
def enableTrain(self):
self.trainbox.setEnabled(True)
self.trainNewInput.setEnabled(True)
self.testbox.setEnabled(False)
def addInputTextToListbox(self):
print("Hello world!!!")
def t_DefaultData(self):
ann = NumberIA()
t = self.vtrain.text()
print("Training data: ", t)
global train
global train_r
global test
global test_r
train, train_r, test, test_r = ann.read_file(float(t))
self.output.setText("Train complete...")
ann.crear_red(train, train_r)
accuracy, matrix = ann.probar_red(test, test_r)
self.output_2.setText("Accuracy: " + str(accuracy * 100) + "%")
print("Matris de Confusion:")
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in matrix]))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = MyFirstGuiProgram(MainWindow)
MainWindow.show()
MainWindow.setWindowTitle("RNA: Inteligencia Artificial 2")
ui.enableTrain()
sys.exit(app.exec_())
I cant seem to find examples on how to to this online, the examples I have found are vague to me and cant seem to figure it out.
I recommend you inherit from QMainWindow and implement the Ui_MainWindow interface, to draw in a QGraphicsView you must use a QGraphicsScene, and use its methods, in this case use addRect().
from PyQt5 import QtCore, QtGui, QtWidgets
class MyFirstGuiProgram(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent=parent)
self.setupUi(self)
scene = QtWidgets.QGraphicsScene()
self.graphicsView.setScene(scene)
pen = QtGui.QPen(QtCore.Qt.green)
side = 20
for i in range(16):
for j in range(16):
r = QtCore.QRectF(QtCore.QPointF(i*side, j*side), QtCore.QSizeF(side, side))
scene.addRect(r, pen)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MyFirstGuiProgram()
w.show()
sys.exit(app.exec_())
You can also draw it by QLineF(), it gives more control from design point of view.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def sceneWithPen(grid):
scene = QGraphicsScene()
view = QGraphicsView()
view.setScene(scene)
# Creating line's colors
red = QColor(qRgb(172, 50, 99))
blue = QColor(qRgb(50, 150, 203))
# Set length of square's side and number of horizontal and vertical lines
vLines = 16
hLines = 16
side = 30
# Set starting values for loops
hor = 0
ver = 0
subdiv = 16
leftX,leftY = 0, 0
rightX, rightY = subdiv*side, 0
bottomX, bottomY= 0, 0
topX, topY = 0, subdiv*side
while ver < vLines:
# Drawing vertical lines
ver = ver + 1
vLine = QLineF(bottomX, bottomY, topX, topY)
bottomX, topX = bottomX + side, topX + side
scene.addLine(vLine, red)
while hor < hLines:
#Drawing horizontal lines
hor = hor + 1
hLine = QLineF(leftX, leftY, rightX, rightY)
leftY, rightY = leftY + side, rightY + side
scene.addLine(hLine, blue)
grid.addWidget(view)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
grid = QGridLayout()
sceneWithPen(grid)
w.setLayout(grid)
w.show()
sys.exit(app.exec_())
It will be like this:
Great example #eyllanesc just gave you right above, here is another small example I just happened to have laying around, if you need to draw like a simple free hand.
Have your MainWindow, for example a QMainWindow or Qwidget or...
Have a QGraphicsView.
Set the QGraphicsView's scene with your QGraphicsScene
Have your own QGraphicsPathItem so you can set properties you need.
Have the implementation of what you want to draw inside your scene, so it knows how to draw on itself.
Having things in this way you will have control of several scenes knowing how to draw on itself independently, of course if you will need more than one scene.
This example the logic were implemented inside the QGraphicsView, you could move it to your GraphicsScene.
class MainWindow(QMainWindow):
central_widget = None
layout_container = None
def __init__(self):
super(MainWindow, self).__init__()
self.central_widget = QWidget()
self.layout_container = QVBoxLayout()
self.central_widget.setLayout(self.layout_container)
self.setCentralWidget(self.central_widget)
self.layout_container.addWidget(GraphicsView())
class GraphicsView(QGraphicsView):
start = None
end = None
item = None
path = None
def __init__(self):
super(GraphicsView, self).__init__()
self.setScene(QGraphicsScene())
self.path = QPainterPath()
self.item = GraphicsPathItem()
self.scene().addItem(self.item)
def mousePressEvent(self, event):
self.start = self.mapToScene(event.pos())
self.path.moveTo(self.start)
def mouseMoveEvent(self, event):
self.end = self.mapToScene(event.pos())
self.path.lineTo(self.end)
self.start = self.end
self.item.setPath(self.path)
class GraphicsPathItem(QGraphicsPathItem):
def __init__(self):
super(GraphicsPathItem, self).__init__()
pen = QPen()
pen.setColor(Qt.black)
pen.setWidth(10)
self.setPen(pen)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())

How to associate a horizontal scrollbar to multiple groupbox.?

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_())

Categories

Resources