Dery
Dery

Reputation: 327

How to set a child item of a QTreeWidget tobe auto selected and highlighted when click on its parent

Here is my code ,it will work for sometime but most times don't. I have searched for this but the solutions just don't work.

(I am using pyside2, not pyqt5)

Click parent

AutoSelect child

import sys
import time

from PySide2.QtWidgets import QWidget,QPushButton,QApplication,QListWidget,QGridLayout,\
QLabel,QMainWindow,QLineEdit,QScrollArea,QVBoxLayout,QMessageBox,QComboBox,QMenu,QAction,\
QDialog,QTreeWidget,QTreeWidgetItem,QSlider,QAbstractItemView,QHBoxLayout
from PySide2.QtCore import QTimer,QDateTime,QSize,Qt,Signal,Slot,QThread,QMutex,QMutexLocker,QItemSelectionModel
from PySide2.QtGui import *


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.resize(320, 300)
        self.setWindowTitle("--")
        self.setStyleSheet(
            """
            QMainWindow
            {
                background-color:white;
                color:white;
                margin:0px
            }
            """
        )
        self.InitializeWindow()

    def InitializeWindow(self):
        self.center = QWidget(self)
        self.center.setGeometry(0, 0, 320, 300); 
        layout=QHBoxLayout()

        self.tree=QTreeWidget()
        self.tree.setColumnCount(1)
        self.tree.setHeaderLabels(['func'])

        root1=QTreeWidgetItem(self.tree)
        root1.setText(0,'-A')

        self.tree.setColumnWidth(0,100)
        self.child1_1=QTreeWidgetItem(root1)
        self.child1_1.setText(0,'--aa')

        self.child1_2=QTreeWidgetItem(root1)
        self.child1_2.setText(0,'--bb')

        root2=QTreeWidgetItem(self.tree)
        root2.setText(0,'-B')

        self.child2_1=QTreeWidgetItem(root2)
        self.child2_1.setText(0,'--cc')

        self.child2_2=QTreeWidgetItem(root2)
        self.child2_2.setText(0,'--dd')

        self.child2_3=QTreeWidgetItem(root2)
        self.child2_3.setText(0,'--ee')

        self.tree.addTopLevelItem(root1)
        self.tree.addTopLevelItem(root2)

        self.area_op=QWidget()
        self.area_op.setMinimumWidth(100)
        self.area_op.setStyleSheet(
            '''QWidget
            {
                background-color:white;
                color:white;
                font-size:15px;
                border:0px solid #708090;
                margin:0px
            }'''
            )

        self.tree.currentItemChanged.connect(self.tree_onClick)

        layout.addWidget(self.tree)
        layout.addWidget(self.area_op)
        self.center.setLayout(layout)
        self.show()

    def tree_onClick(self):
        getSelected = self.tree.currentItem()
        #print(str(sys._getframe().f_lineno),getSelected)
        if getSelected:
            if(getSelected.text(0)=='--cc'):
                pass
            elif(getSelected.text(0)=="-A"):
                getSelected.setExpanded(True)
                self.tree.setCurrentItem(self.child1_1)
            elif(getSelected.text(0)=="-B"):
                getSelected.setExpanded(True)
                self.tree.setCurrentItem(self.child2_1,0,QItemSelectionModel.Select)
                if self.child2_1.isSelected()==False:
                    self.child2_1.setSelected(True)
            else:
                pass
        else:
            print(str(sys._getframe().f_lineno),"tree error ",getSelected)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Upvotes: 2

Views: 1654

Answers (1)

musicamante
musicamante

Reputation: 48260

If you want to automatically select the first child, you shouldn't check for the item text, but if it actually has child items.

Also, using currentItemChanged might not be a good idea, as that signal might create some inconstinstency if you're trying to change the current item as its result (which might be the source of your problem, even if I wasn't able to reproduce it).

The solution is to use the itemClicked() signal instead, and also take advantage of its first argument (the clicked item).

        # ...
        self.tree.itemClicked.connect(self.tree_onClick)
        # ...

    def tree_onClick(self, item, column):
        if item.childCount():
            self.tree.setCurrentItem(item.child(0))

Upvotes: 2

Related Questions