无法从QWidg更改QSlider的值

2024-06-01 03:14:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从另一个QWidget更改一个QWidget的值,但是什么都没有发生。我用这一行从每个过滤器对象调用changeValue函数:

self.filter1.valueChanged.connect(self.filter1.changeValue)

我已经将print(value)语句放在changeValue方法中,以查看是否正在调用该方法,但它没有被调用。在

这是我的代码:

^{pr2}$

Tags: 对象方法函数代码self过滤器valueconnect
1条回答
网友
1楼 · 发布于 2024-06-01 03:14:40

问题是您从QSlider继承,同时在该类中创建一个名为thresh_sld的属性,这是视图中显示的元素,但没有连接到ChangeValue的滑块是{}类滑块。在

使用简单的解决方案是将属性thresh_sld的信号连接到提供的插槽,必须更改以下内容:

self.filter1.valueChanged.connect(self.filter1.changeValue)
self.filter2.valueChanged.connect(self.filter2.changeValue)

收件人:

^{pr2}$

一个更优雅的解决方案是将Filter基类从QSlider更改为QWidget,并将标签和QSlider添加到其布局中。在

class Filter(QWidget):
    """Common base for all filters"""
    defaultK = 3
    filterCount = 0

    def __init__(self):
        super(Filter, self).__init__()
        lay = QVBoxLayout(self)

        # Variable for the constant of the OpenCV filter
        self.k = 3

        # Label for the slider
        self.k_lbl = QLabel(str(self.k))

        # Increase the number of filters created
        Filter.filterCount += 1

        # Slider for the first OpenCV filter, with min, max, default and step values
        self.thresh_sld = QSlider(Qt.Horizontal, self)
        self.thresh_sld.setFocusPolicy(Qt.NoFocus)
        self.thresh_sld.setMinimum(3)
        self.thresh_sld.setMaximum(51)
        self.thresh_sld.setValue(self.k)
        self.thresh_sld.setSingleStep(2)
        self.thresh_sld.valueChanged.connect(self.changeValue)

        lay.addWidget(self.k_lbl)
        lay.addWidget(self.thresh_sld)

    def changeValue(self, value):
        # Function for setting the value of k1

        print(value)

        if value % 2 == 1:
            self.k = value
        else:
            self.k = value + 1

        self.thresh_sld.setValue(self.k)
        self.k_lbl.setText(str(self.k))

class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.filter1 = Filter()
        self.filter2 = Filter()

        # Creates the main layout (vertical)
        v_main_lay = QVBoxLayout()
        # Adds the sliders and their labels to the bottom of the main layout
        v_main_lay.addWidget(self.filter1)
        v_main_lay.addWidget(self.filter2)

        # Sets the main layout
        self.setLayout(v_main_lay)

        # Sets the geometry, position, window title and window default mode
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Review')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

相关问题 更多 >