我需要Qwidget和QTreeWidgets支持我的小软件。见下图。在
这就是我的Qwidget的样子。当我关闭窗口并用先前的选择恢复它时,我想恢复Qtreewidget项和小部件。如图所示下面。作为在下面的脚本中,我使用了Qsettings,我试图用pickle来修复它,但是没有用。在
编码方面的任何改进都是值得欢迎的。在
from PyQt5 import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import*
from PyQt5.QtGui import *
import sys
import pickle
iconroot = QFileInfo(__file__).absolutePath()
ORGANIZATION_NAME = 'Circularcolumn App'
ORGANIZATION_DOMAIN = 'Circular shape'
APPLICATION_NAME = 'QSettings program'
SETTINGS_TRAY = 'settings/tray'
class usedcircularshape(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Frequently used shape")
self.setWindowIcon(QIcon(iconroot+"/images/circularcolumnnorebar.png"))
#self.setStyleSheet("background-color:#f2f2f2")
self.addbutton = QPushButton("Add")
self.addbutton.clicked.connect(self.add)
self.deletebutton = QPushButton("Delete")
self.deletebutton.clicked.connect(self.delete)
self.okbutton = QPushButton("Ok")
self.okbutton.setCursor(Qt.PointingHandCursor)
#self.okbutton.clicked.connect(self.hidethiswindow)
self.okbutton.clicked.connect(self.savesetting)
self.cancelbutton = QPushButton("Cancel")
self.cancelbutton.setCursor(Qt.PointingHandCursor)
self.cancelbutton.clicked.connect(self.loadsetting)
#self.cancelbutton.clicked.connect(self.close)
self.addimage()
self.qlabeltodefinesection()
self.treewidget()
self.sectionnamecircular = QLabel('Section name: ')
self.sectionnamecircularindata = QLineEdit('Define en name to section')
self.sectionnamecircularindata.setObjectName("sectionnamecircularindata")
self.sectionnamecircular.setBuddy(self.sectionnamecircularindata)
self.sectionnamecircular.setFocus()
self.grid_sectionname = QHBoxLayout()
self.grid_sectionname.addWidget(self.sectionnamecircular)
self.grid_sectionname.addWidget(self.sectionnamecircularindata)
self.boxlayout = QGridLayout()
self.boxlayout.addLayout(self.grid_sectionname,0,0,1,2)
self.boxlayout.addWidget(self.treewidget,1,0,5,2)
self.boxlayout.addWidget(self.addbutton,2,2)
self.boxlayout.addWidget(self.deletebutton,3,2)
self.boxlayout.addWidget(self.imagelabel,6,0)
self.boxlayout.addLayout(self.qlabelhboxgrid ,6,1)
self.boxlayout.addWidget(self.okbutton,8,1)
self.boxlayout.addWidget(self.cancelbutton,8,2)
self.setLayout(self.boxlayout)
try:
self.loadsetting()
except ( ValueError, TypeError):
pass
def treewidget(self):
self.treewidget = QTreeWidget(self)
self.treewidget.setColumnCount(1)
self.treewidget.setColumnWidth(1,20)
self.treewidget.setHeaderItem(QTreeWidgetItem(['Standard Section Library']))
#self.treewidget.addTopLevelItem(QTreeWidgetItem(['Standard Sectiontype']))
self.treewidget.setRootIsDecorated(True)
self.firstparentitem = QTreeWidgetItem(self.treewidget)
self.firstparentitem.setText(0,'Circular shapes')
self.firstparentitem.setIcon(0,QIcon(iconroot+"/images/circularcolumnnorebar.png"))
standardsectionlist = ["D100","D150","D200","D250","D300","D350","D400","D450","D500","D550","D600","D650"
,"D700","D750","D800","D850","D900","D950","D1000"]
for i in standardsectionlist:
self.firstparentitem.addChild(QTreeWidgetItem(["%s"%i]))
self.secondparentitem = QTreeWidgetItem(self.treewidget)
self.secondparentitem.setText(0,'Customized')
self.secondparentitem.setIcon(0,QIcon(iconroot+"/images/circularcolumnnorebar.png"))
self.secondchilditem = QTreeWidgetItem(["D235"])
self.secondparentitem.insertChild(0,self.secondchilditem)
self.secondchilditem.setChildIndicatorPolicy(QTreeWidgetItem.DontShowIndicator)
self.treewidget.move(15,15)
self.treewidget.setGeometry(15,15,200,600)
self.treewidget.setAlternatingRowColors(True)
self.treewidget.expandItem ( self.firstparentitem )
self.show()
print(self.treewidget.headerItem().text(0))
print(self.treewidget.columnCount())
print(self.treewidget.currentColumn())
print(self.treewidget.indexFromItem(self.firstparentitem).row())
print(self.firstparentitem.childCount())
print(self.firstparentitem.child(1).text(0))
print(self.firstparentitem.text(0))
print(self.treewidget.headerItem().text(0))
print(self.treewidget.topLevelItem(0).text(0))
print(self.firstparentitem.isSelected())
print(self.treewidget.selectedItems())
print(self.secondchilditem.text(1))
branchstyle = '''QTreeWidget {border:none;}
QTreeView::branch:has-siblings:!adjoins-item {
border-image: url(images/vline.png) 0;}
QTreeView::branch:has-siblings:adjoins-item {
border-image: url(images/branch-more.png) 0;}
QTreeView::branch:!has-children:!has-siblings:adjoins-item {
border-image: url(images/branch-end.png) 0;}
QTreeView::branch:has-children:!has-siblings:closed,
QTreeView::branch:closed:has-children:has-siblings {
border-image: none;
image: url(images/branch-closed.png);}
QTreeView::branch:open:has-children:!has-siblings,
QTreeView::branch:open:has-children:has-siblings {
border-image: none;
image: url(images/branch-open.png);}'''
self.treewidget.setStyleSheet(branchstyle)
self.treewidget.itemClicked.connect(self.currentitem)
self.treewidget.currentItemChanged.connect(self.current_item_changed)
#@QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, QtWidgets.QTreeWidgetItem)
def current_item_changed(self, current, previous):
#print('\ncurrent: {}, \nprevious: {}'.format(current, previous))
print(current.text(0),previous)
def add(self):
text, ok = QInputDialog.getText(self, "Add custom section", "Enter section geometry f.ex as D325 or just 325 in mm: ")
if ok:
self.secondchilditem = QTreeWidgetItem(["%s"% text])
self.secondparentitem.insertChild(0,self.secondchilditem)
self.treewidget.expandItem ( self.secondparentitem )
self.gettext = text
print(self.secondparentitem.child(0), self.gettext)
def delete(self):
self.secondparentitem.takeChild(0)
def currentitem(self):
print(self.treewidget.currentItem().text(0),self.treewidget.selectedItems())
self.itemtext = self.treewidget.currentItem().text(0)
if self.itemtext == self.firstparentitem.text(0) or self.itemtext == self.secondparentitem.text(0):
return None
elif self.itemtext == self.treewidget.topLevelItem(0).text(0):
return None
elif self.itemtext == None:
return None
else:
self.select_circular_section = int(self.itemtext.translate({ord('D'):None}))
print(self.itemtext, self.treewidget.selectedItems, self.select_circular_section)
area = str(format(3.1416/4*(self.select_circular_section)**2,'0.2E'))
inerti = str(format(3.1416/64*pow(self.select_circular_section,4),'0.2E'))
self.qlabelcirculardiameterselected = QLabel('')
qlabelcircularareaselected = QLabel('')
qlabelcircularinertimomentselected = QLabel("")
emptylabel1 = QLabel(' ')
self.qlabelcirculardiameterselected.setText('%s mm '% self.select_circular_section)
qlabelcircularareaselected.setText('{} mm2 ' .format(area))
qlabelcircularinertimomentselected.setText("%s mm4 " %(inerti))
qlabelhboxgridselected = QGridLayout()
qlabelhboxgridselected.addWidget(emptylabel1,0,0)
qlabelhboxgridselected.addWidget(self.qlabelcirculardiameterselected,1,0)
qlabelhboxgridselected.addWidget(qlabelcircularareaselected,2,0)
qlabelhboxgridselected.addWidget(qlabelcircularinertimomentselected,3,0)
qlabelhboxgridselected.addWidget(emptylabel1,4,0,5,0)
return print(self.itemtext, self.treewidget.selectedItems, self.select_circular_section), self.boxlayout.addLayout(qlabelhboxgridselected ,6,2),self.qlabelcirculardiameterselected
def addimage(self):
self.imagelabel = QLabel()
self.circularimage = QPixmap(iconroot+"/images/circularcolumnnorebard.png").scaled(230,230,Qt.KeepAspectRatio)
self.imagelabel.setPixmap(self.circularimage)
self.imagelabel.setGeometry(15,15,15,15)
def hidethiswindow(self):
if self.itemtext == self.firstparentitem.text(0) or self.itemtext == self.secondparentitem.text(0):
QMessageBox.about(self,'Error selection','Please, select a section not a text')
elif self.itemtext == self.treewidget.topLevelItem(0).text(0):
QMessageBox.about(self,'Error selection','Please, select a section not a text')
elif self.itemtext == None:
QMessageBox.about(self,'Error selection','Please, select a section not a text')
else:
self.savesetting()
self.hide()
def qlabeltodefinesection(self):
self.qlabelcirculardiameter = QLabel(' D = ')
self.qlabelcirculararea = QLabel(' A = ')
self.qlabelcircularinertimoment = QLabel(" I = ")
self.emptylabel = QLabel(' ')
self.qlabelhboxgrid = QGridLayout()
self.qlabelhboxgrid.addWidget(self.emptylabel,0,0)
self.qlabelhboxgrid.addWidget(self.qlabelcirculardiameter,1,0)
self.qlabelhboxgrid.addWidget(self.qlabelcirculararea,2,0)
self.qlabelhboxgrid.addWidget(self.qlabelcircularinertimoment,3,0)
self.qlabelhboxgrid.addWidget(self.emptylabel,4,0,5,0)
def savesetting(self):
settings = QSettings(ORGANIZATION_NAME,APPLICATION_NAME)
#settings = QSettings('config.ini',QSettings.IniFormat)
settings.beginGroup('D')
settings.setValue(SETTINGS_TRAY,self.geometry())
settings.setValue("LineEdit",self.sectionnamecircularindata.text())
settings.setValue("Selectitem",self.treewidget.currentItem())
settings.setValue("Label",self.qlabelcirculardiameterselected)
settings.endGroup()
print('Saved', )
#self.hide()
def loadsetting(self):
settings = QSettings(ORGANIZATION_NAME,APPLICATION_NAME)
#settings = QSettings('config.ini',QSettings.IniFormat)
settings.beginGroup('D')
myrect = settings.value(SETTINGS_TRAY)
restorelineEdit = settings.value("LineEdit",'')
restoreselectsection = settings.value("Selectitem",)
restoreqlabel = settings.value("Label",'')
self.setGeometry(myrect)
self.sectionnamecircularindata.setText(restorelineEdit)
self.treewidget.setCurrentItem(restoreselectsection)
settings.endGroup()
if __name__ == "__main__":
QCoreApplication.setApplicationName(ORGANIZATION_NAME)
QCoreApplication.setOrganizationDomain(ORGANIZATION_DOMAIN)
QCoreApplication.setApplicationName(APPLICATION_NAME)
app = QApplication(sys.argv)
subwindow=usedcircularshape()
subwindow.show()
app.exec()
代码是做什么的?在
这是一个工程软件,对于混凝土柱,其想法是用户应该能够选择一个标准截面,例如D350,D表示直径,350是圆形混凝土柱的直径单位mm。 用户可以添加圆形柱的自定义形状。当用户单击并从Qtreewidget中选择一个部分时,这个部分应该保留下来,并且是全局的,可以用于进一步的计算,这并没有显示给她。这是一个在大型具体软件中定义几何图形的小部件。 下面我将进一步解释代码。 首先,我创建Qdialog并创建Qtreewidget,一个用于澄清的图像和基于Qlabel的项目选择。 在Qtreewidget中,我首先创建一个parentitem并给它起一个名字“圆形”
^{pr2}$然后parentitem有子项,要定义和添加这些子项,首先我创建一个包含标准节的列表
standardsectionlist = ["D100","D150","D200","D250","D300","D350","D400","D450","D500","D550","D600","D650"
,"D700","D750","D800","D850","D900","D950","D1000"]
和do for condition将子项添加到parentitem。在
for i in standardsectionlist:
self.firstparentitem.addChild(QTreeWidgetItem(["%s"%i]))
稍后,我定义了第二个parentitem,并给出了一个名称“Customized”,然后定义了一个列表项,然后将该列表项作为子项添加到第二个parentitem中。 对于用户应该能够添加和删除子项从第二个父项我创建2个按钮
self.addbutton = QPushButton("Add")
self.deletebutton = QPushButton("Delete")
Addbutton有一个将子项添加到第二个parentitem的函数。 Deletebutton具有从第二个parentitem中删除第一个子项的函数。在
def currentitem(self):
currentitem函数有一个函数,当用户在Qtreewidget中点击并选择一个项目时,它会获取currenitem文本并从中删除D字母,并将其转换为int,然后显示为D=Diameter, A=面积等
def hidethiswindow(self)
hidethiswindow函数该函数引导用户选择项目或取消小部件,如果用户错误地选择了headeritem,则会出现一条错误消息,并告诉用户选择子项。太强大了,不是吗!在
剩下的代码是显示和Qsettings。希望这能解释密码。在
你要做的是保存每个项目的数据,为此我创建了itemToTuple方法,它返回要保存的数据的元组,也考虑到保存的元组,你必须设置这些属性,并为此使用tupleToItem函数(如果你想添加项目的更多信息,你只需修改这些方法)。但要保存QTreeWidget的所有项,必须遍历整个树。为此,使用dataFromChild方法返回项及其子项的数据。逆过程,也就是说,给定的数据必须建立在所有的项目中,必须使用dataToChild,这就建立了各个项目及其子项目的数据。在
我还将应用程序分成几个类进行排序,如果您希望保存小部件的信息,则必须创建一个名为writeSettings(…)的方法,其格式与我展示的格式类似,然后应用程序将调用closeEvent(…)方法。类似地,您可以创建readSettings(…)方法并在其构造函数中调用它。在
相关问题 更多 >
编程相关推荐